label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| Code Sample 1:
public static OutputStream getOutputStream(String path) throws ResourceException { URL url = getURL(path); if (url != null) { try { return url.openConnection().getOutputStream(); } catch (IOException e) { throw new ResourceException(e); } } else { throw new ResourceException("Error obtaining resource, invalid path: " + path); } }
Code Sample 2:
protected static URL[] createUrls(URL jarUrls[]) { ArrayList<URL> additionalUrls = new ArrayList<URL>(Arrays.asList(jarUrls)); for (URL ju : jarUrls) { try { JarFile jar = new JarFile(ju.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (j.isDirectory()) continue; if (j.getName().startsWith("lib/") && j.getName().endsWith(".jar")) { URL url = new URL("jar:" + ju.getProtocol() + ":" + ju.getFile() + "!/" + j.getName()); InputStream is = url.openStream(); File tmpFile = File.createTempFile("SCDeploy", ".jar"); FileOutputStream fos = new FileOutputStream(tmpFile); IOUtils.copy(is, fos); is.close(); fos.close(); additionalUrls.add(new URL("file://" + tmpFile.getAbsolutePath())); } } } catch (IOException e) { } } return additionalUrls.toArray(new URL[] {}); } |
00
| Code Sample 1:
public ProgramMessageSymbol addProgramMessageSymbol(int programID, String name, byte[] bytecode) throws AdaptationException { ProgramMessageSymbol programMessageSymbol = null; Connection connection = null; PreparedStatement preparedStatement = null; Statement statement = null; ResultSet resultSet = null; InputStream stream = new ByteArrayInputStream(bytecode); try { String query = "INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES ( ?, ?, ? )"; connection = DriverManager.getConnection(CONN_STR); preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, programID); preparedStatement.setString(2, name); preparedStatement.setBinaryStream(3, stream, bytecode.length); log.info("INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES (" + programID + ", '" + name + "', " + "<bytecode>)"); preparedStatement.executeUpdate(); statement = connection.createStatement(); query = "SELECT * FROM ProgramMessageSymbols WHERE " + "programID = " + programID + " AND " + "name = '" + name + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to add program message symbol failed."; log.error(msg); ; throw new AdaptationException(msg); } programMessageSymbol = getProgramMessageSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in addProgramMessageSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { preparedStatement.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programMessageSymbol; }
Code Sample 2:
private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri, ClientConnectionManager connectionManager) { InputStream contentInput = null; if (connectionManager == null) { try { URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); conn.connect(); contentInput = conn.getInputStream(); } catch (Exception e) { Log.w(TAG, "Request failed: " + uri); e.printStackTrace(); return null; } } else { final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS); HttpUriRequest request = new HttpGet(uri); HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { contentInput = entity.getContent(); } } catch (Exception e) { Log.w(TAG, "Request failed: " + request.getURI()); return null; } } if (contentInput != null) { return new BufferedInputStream(contentInput, 4096); } else { return null; } } |
00
| Code Sample 1:
private BundleURLClassPath createBundleURLClassPath(Bundle bundle, Version version, File bundleFile, File cache, boolean alreadyCached) throws Exception { String bundleClassPath = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClassPath == null) { bundleClassPath = "."; } ManifestEntry[] entries = ManifestEntry.parse(bundleClassPath); String[] classPaths = new String[0]; for (int i = 0; i < entries.length; i++) { String classPath = entries[i].getName(); if (classPath.startsWith("/")) { classPath = classPath.substring(1); } if (classPath.endsWith(".jar")) { try { File file = new File(cache, classPath); if (!alreadyCached) { file.getParentFile().mkdirs(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(classPath).toString(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } else { if (!file.exists()) { throw new IOException(new StringBuilder("classpath ").append(classPath).append(" not found").toString()); } } } catch (IOException e) { FrameworkEvent frameworkEvent = new FrameworkEvent(FrameworkEvent.INFO, bundle, e); framework.postFrameworkEvent(frameworkEvent); continue; } } classPaths = (String[]) ArrayUtil.add(classPaths, classPath); } if (!alreadyCached) { String bundleNativeCode = (String) bundle.getHeaders().get(Constants.BUNDLE_NATIVECODE); if (bundleNativeCode != null) { entries = ManifestEntry.parse(bundleNativeCode); for (int i = 0; i < entries.length; i++) { ManifestEntry entry = entries[i]; String libPath = entry.getName(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(libPath).toString(); File file = new File(cache, libPath); file.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } } } BundleURLClassPath urlClassPath = new BundleURLClassPathImpl(bundle, version, classPaths, cache); return urlClassPath; }
Code Sample 2:
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { String pathInfo = httpServletRequest.getPathInfo(); log.info("PathInfo: " + pathInfo); if (pathInfo == null || pathInfo.equals("") || pathInfo.equals("/")) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String fileName = pathInfo.charAt(0) == '/' ? pathInfo.substring(1) : pathInfo; log.info("FileName: " + fileName); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = getDataSource().getConnection(); ps = con.prepareStatement("select file, size from files where name=?"); ps.setString(1, fileName); rs = ps.executeQuery(); if (rs.next()) { httpServletResponse.setContentType(getServletContext().getMimeType(fileName)); httpServletResponse.setContentLength(rs.getInt("size")); OutputStream os = httpServletResponse.getOutputStream(); org.apache.commons.io.IOUtils.copy(rs.getBinaryStream("file"), os); os.flush(); } else { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (SQLException e) { throw new ServletException(e); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (ps != null) try { ps.close(); } catch (SQLException e) { } if (con != null) try { con.close(); } catch (SQLException e) { } } } |
00
| Code Sample 1:
public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } |
00
| Code Sample 1:
public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } try { String fichTable; if (sys) { fichTable = ConfigNat.getInstallFolder() + "/xsl/tablesEmbosseuse/" + tableBraille; } else { fichTable = ConfigNat.getUserEmbossTableFolder() + "/" + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(ConfigNat.getUserTempFolder() + "Table_pour_chaines.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
@Override public String encodePassword(String rawPass, Object salt) throws DataAccessException { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.reset(); digest.update(((String) salt).getBytes("UTF-8")); return new String(digest.digest(rawPass.getBytes("UTF-8"))); } catch (Throwable e) { throw new DataAccessException("Error al codificar la contrase�a", e) { private static final long serialVersionUID = 3880106673612870103L; }; } } |
00
| Code Sample 1:
@Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } }
Code Sample 2:
public static String encryptPassword(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { LOG.error(e); } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e); } return (new BASE64Encoder()).encode(md.digest()); } |
00
| Code Sample 1:
private Response postRequest(String urlString, String params) throws Exception { URL url = new URL(urlString); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoInput(true); uc.setDoOutput(true); uc.setUseCaches(false); uc.setAllowUserInteraction(false); uc.setRequestMethod("POST"); uc.setRequestProperty("ContentType", "application/x-www-form-urlencoded"); uc.setRequestProperty("User-Agent", "CytoLinkFromMJ"); if (cookie != null) uc.setRequestProperty("Cookie", cookie); PrintStream out = new PrintStream(uc.getOutputStream()); out.print(params); out.flush(); out.close(); uc.connect(); StringBuffer sb = new StringBuffer(); String inputLine; BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); while ((inputLine = in.readLine()) != null) { sb.append(inputLine + "\n"); } in.close(); Response res = new Response(); res.content = sb.toString(); res.contentType = uc.getHeaderField("Content-Type"); res.cookie = uc.getHeaderField("Set-Cookie"); return res; }
Code Sample 2:
protected Scanner createScanner(InputSource source) { documentURI = source.getURI(); if (documentURI == null) { documentURI = ""; } Reader r = source.getCharacterStream(); if (r != null) { return new Scanner(r); } InputStream is = source.getByteStream(); if (is != null) { return new Scanner(is, source.getEncoding()); } String uri = source.getURI(); if (uri == null) { throw new CSSException(formatMessage("empty.source", null)); } try { ParsedURL purl = new ParsedURL(uri); is = purl.openStreamRaw(CSSConstants.CSS_MIME_TYPE); return new Scanner(is, source.getEncoding()); } catch (IOException e) { throw new CSSException(e); } } |
00
| Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
public static String getFileContents(String path) { BufferedReader buffReader = null; InputStream stream = null; if (path.indexOf("://") != -1) { URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { LOGGER.warn(String.format("Malformed URL: \"%s\"", path)); } if (url == null) { throw new DeveloperError(String.format("Cannot create URL from path: \"%s\"", path), new NullPointerException()); } try { String encoding = Characters.getDeclaredXMLEncoding(url); stream = url.openStream(); buffReader = new BufferedReader(new InputStreamReader(stream, encoding)); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", path)); } } else { File toRead = null; try { toRead = getExistingFile(path); } catch (FileNotFoundException e) { throw new UserError(new FileNotFoundException(path)); } if (toRead.isAbsolute()) { String parent = toRead.getParent(); try { workingDirectory.push(URLTools.createValidURL(parent)); } catch (FileNotFoundException e) { throw new DeveloperError(String.format("Created an invalid parent file: \"%s\".", parent), e); } } if (toRead.exists() && !toRead.isDirectory()) { String _path = toRead.getAbsolutePath(); try { String encoding = Characters.getDeclaredXMLEncoding(URLTools.createValidURL(_path)); stream = new FileInputStream(_path); buffReader = new BufferedReader(new InputStreamReader(stream, encoding)); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", _path)); return null; } } else { assert toRead.exists() : "getExistingFile() returned a non-existent file"; if (toRead.isDirectory()) { throw new UserError(new FileAlreadyExistsAsDirectoryException(toRead)); } } } StringBuilder result = new StringBuilder(); String line; if (buffReader != null && stream != null) { try { while ((line = buffReader.readLine()) != null) { result.append(line); } buffReader.close(); stream.close(); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", path)); return null; } } return result.toString(); } |
00
| Code Sample 1:
public static byte[] ComputeForText(String ThisString) throws Exception { byte[] Result; MessageDigest MD5Hasher; MD5Hasher = MessageDigest.getInstance("MD5"); MD5Hasher.update(ThisString.replaceAll("\r", "").getBytes("iso-8859-1")); Result = MD5Hasher.digest(); return Result; }
Code Sample 2:
private void redownloadResource(SchemaResource resource) { if (_redownloadSet != null) { if (_redownloadSet.contains(resource)) return; _redownloadSet.add(resource); } String filename = resource.getFilename(); String schemaLocation = resource.getSchemaLocation(); String digest = null; if (schemaLocation == null || filename == null) return; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { URL url = new URL(schemaLocation); URLConnection conn = url.openConnection(); conn.addRequestProperty("User-Agent", USER_AGENT); conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); DigestInputStream input = digestInputStream(conn.getInputStream()); IOUtil.copyCompletely(input, buffer); digest = HexBin.bytesToString(input.getMessageDigest().digest()); } catch (Exception e) { warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); return; } if (digest.equals(resource.getSha1()) && fileExists(filename)) { warning("Resource " + filename + " is unchanged from " + schemaLocation + "."); return; } try { InputStream source = new ByteArrayInputStream(buffer.toByteArray()); writeInputStreamToFile(source, filename); } catch (IOException e) { warning("Could not write to file " + filename + " for " + schemaLocation + ":" + e.getMessage()); return; } warning("Refreshed " + filename + " from " + schemaLocation); } |
11
| Code Sample 1:
public static void copyFile(File source, File destination) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[4096]; int read = -1; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.flush(); out.close(); in.close(); }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { logger.error(Logger.SECURITY_FAILURE, "Problem encoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
private void addIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst = null; try { conn = getConnection(); pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst.setInt(1, id); pst.setString(2, ingBean.getName()); pst.setDouble(3, ingBean.getAmount()); pst.setInt(4, ingBean.getType()); pst.setInt(5, ingBean.getShopFlag()); pst.executeUpdate(); } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst != null) pst.close(); pst = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } }
Code Sample 2:
public void deleteGroup(String groupID) throws XregistryException { try { Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_GROUP_SQL_MAIN); statement1.setString(1, groupID); int updateCount = statement1.executeUpdate(); if (updateCount == 0) { throw new XregistryException("Database is not updated, Can not find such Group " + groupID); } if (cascadingDeletes) { PreparedStatement statement2 = connection.prepareStatement(DELETE_GROUP_SQL_DEPEND); statement2.setString(1, groupID); statement2.setString(2, groupID); statement2.executeUpdate(); } connection.commit(); groups.remove(groupID); log.info("Delete Group " + groupID + (cascadingDeletes ? " with cascading deletes " : "")); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } } |
11
| Code Sample 1:
public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
Code Sample 2:
public static byte[] md5raw(String data) { try { MessageDigest md = MessageDigest.getInstance(MD); md.update(data.getBytes(UTF8)); return md.digest(); } catch (Exception e) { throw new RuntimeException(e); } } |
00
| Code Sample 1:
public void testReleaseOnEntityWriteTo() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); assertEquals(1, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
Code Sample 2:
public osid.shared.Id ingest(String fileName, String templateFileName, String fileType, File file, Properties properties) throws osid.dr.DigitalRepositoryException, java.net.SocketException, java.io.IOException, osid.shared.SharedException, javax.xml.rpc.ServiceException { long sTime = System.currentTimeMillis(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA:fileName =" + fileName + "fileType =" + fileType + "t = 0"); String host = FedoraUtils.getFedoraProperty(this, "admin.ftp.address"); String url = FedoraUtils.getFedoraProperty(this, "admin.ftp.url"); int port = Integer.parseInt(FedoraUtils.getFedoraProperty(this, "admin.ftp.port")); String userName = FedoraUtils.getFedoraProperty(this, "admin.ftp.username"); String password = FedoraUtils.getFedoraProperty(this, "admin.ftp.password"); String directory = FedoraUtils.getFedoraProperty(this, "admin.ftp.directory"); FTPClient client = new FTPClient(); client.connect(host, port); client.login(userName, password); client.changeWorkingDirectory(directory); client.setFileType(FTP.BINARY_FILE_TYPE); client.storeFile(fileName, new FileInputStream(file.getAbsolutePath().replaceAll("%20", " "))); client.logout(); client.disconnect(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Writting to FTP Server:" + (System.currentTimeMillis() - sTime)); fileName = url + fileName; int BUFFER_SIZE = 10240; StringBuffer sb = new StringBuffer(); String s = new String(); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(new File(getResource(templateFileName).getFile().replaceAll("%20", " ")))); byte[] buf = new byte[BUFFER_SIZE]; int ch; int len; while ((len = fis.read(buf)) > 0) { s = s + new String(buf); } fis.close(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Read Mets File:" + (System.currentTimeMillis() - sTime)); String r = updateMetadata(s, fileName, file.getName(), fileType, properties); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Resplaced Metadata:" + (System.currentTimeMillis() - sTime)); File METSfile = File.createTempFile("vueMETSMap", ".xml"); FileOutputStream fos = new FileOutputStream(METSfile); fos.write(r.getBytes()); fos.close(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Ingest complete:" + (System.currentTimeMillis() - sTime)); String pid = "Method Not Supported any more"; System.out.println(" METSfile= " + METSfile.getPath() + " PID = " + pid); return new PID(pid); } |
00
| Code Sample 1:
private static String getWebPage(String urlString) throws Exception { URL url; HttpURLConnection conn; BufferedReader rd; String line; StringBuilder result = new StringBuilder(); try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); }
Code Sample 2:
public static void forEachLine(final URL url, final LineListener lit, final String encoding) { try { ReaderUtils.forEachLine(url.openStream(), lit); } catch (final IOException ioe) { lit.exception(ioe); } } |
00
| Code Sample 1:
public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + File.separatorChar + list[i]; String src1 = src.getAbsolutePath() + File.separatorChar + list[i]; copyFiles(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
Code Sample 2:
public String getLastReleaseVersion() throws TransferException { try { URL url = new URL("http://jtbdivelogbook.sourceforge.net/version.properties"); URLConnection urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setReadTimeout(20000); urlConn.setConnectTimeout(10000); Properties props = new Properties(); InputStream is = urlConn.getInputStream(); props.load(is); is.close(); String lastVersion = props.getProperty(PROPERTY_LAST_RELEASE); if (lastVersion == null) { LOGGER.warn("Couldn't find property " + PROPERTY_LAST_RELEASE); } return lastVersion; } catch (MalformedURLException e) { LOGGER.error(e); throw new TransferException(e); } catch (IOException e) { LOGGER.error(e); throw new TransferException(e); } } |
11
| Code Sample 1:
public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; }
Code Sample 2:
public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } } |
11
| Code Sample 1:
public void run() { BufferedReader reader = null; log = "Downloading... " + name; setChanged(); notifyObservers(); try { Date marker = to; int previousSize = 0; list.clear(); do { previousSize = list.size(); URL url = new URL(createLink(from, marker)); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; while ((line = reader.readLine()) != null) { try { IQuoteHistorical quote = parse(line + ","); if (quote != null && !list.contains(quote)) list.add(quote); else System.err.println(line); } catch (ParseException e) { e.printStackTrace(); } } if (list.size() > 0) marker = list.get(list.size() - 1).getData(); } while (marker.after(from) && previousSize != list.size()); log = "download Completed!"; } catch (MalformedURLException e) { e.printStackTrace(); log = e.getMessage(); } catch (IOException e) { e.printStackTrace(); log = e.getMessage(); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); log = e.getMessage(); } } setChanged(); notifyObservers(); }
Code Sample 2:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { if ((this.jTree2.getSelectionPath() == null) || !(this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode)) { Msg.showMsg("Devi selezionare lo stile sotto il quale caricare la ricetta!", this); return; } if ((this.txtUser.getText() == null) || (this.txtUser.getText().length() == 0)) { Msg.showMsg("Il nome utente è obbligatorio!", this); return; } if ((this.txtPwd.getPassword() == null) || (this.txtPwd.getPassword().length == 0)) { Msg.showMsg("La password è obbligatoria!", this); return; } this.nomeRicetta = this.txtNome.getText(); if ((this.nomeRicetta == null) || (this.nomeRicetta.length() == 0)) { Msg.showMsg("Il nome della ricetta è obbligatorio!", this); return; } StyleTreeNode node = null; if (this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode) { node = (StyleTreeNode) this.jTree2.getSelectionPath().getLastPathComponent(); } try { String data = URLEncoder.encode("nick", "UTF-8") + "=" + URLEncoder.encode(this.txtUser.getText(), "UTF-8"); data += "&" + URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(new String(this.txtPwd.getPassword()), "UTF-8"); data += "&" + URLEncoder.encode("id_stile", "UTF-8") + "=" + URLEncoder.encode(node.getIdStile(), "UTF-8"); data += "&" + URLEncoder.encode("nome_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.nomeRicetta, "UTF-8"); data += "&" + URLEncoder.encode("xml_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.xml, "UTF-8"); URL url = new URL("http://" + Main.config.getRemoteServer() + "/upload_ricetta.asp?" + data); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String str = ""; while ((line = rd.readLine()) != null) { str += line; } rd.close(); Msg.showMsg(str, this); doDefaultCloseAction(); } catch (Exception e) { Utils.showException(e, "Errore in upload", this); } reloadTree(); } |
11
| Code Sample 1:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
Code Sample 2:
protected void saveResponse(final WebResponse response, final WebRequest request) throws IOException { counter_++; final String extension = chooseExtension(response.getContentType()); final File f = createFile(request.getUrl(), extension); final InputStream input = response.getContentAsStream(); final OutputStream output = new FileOutputStream(f); try { IOUtils.copy(response.getContentAsStream(), output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } final URL url = response.getWebRequest().getUrl(); LOG.info("Created file " + f.getAbsolutePath() + " for response " + counter_ + ": " + url); final StringBuilder buffer = new StringBuilder(); buffer.append("tab[tab.length] = {code: " + response.getStatusCode() + ", "); buffer.append("fileName: '" + f.getName() + "', "); buffer.append("contentType: '" + response.getContentType() + "', "); buffer.append("method: '" + request.getHttpMethod().name() + "', "); if (request.getHttpMethod() == HttpMethod.POST && request.getEncodingType() == FormEncodingType.URL_ENCODED) { buffer.append("postParameters: " + nameValueListToJsMap(request.getRequestParameters()) + ", "); } buffer.append("url: '" + escapeJSString(url.toString()) + "', "); buffer.append("loadTime: " + response.getLoadTime() + ", "); final byte[] bytes = IOUtils.toByteArray(response.getContentAsStream()); buffer.append("responseSize: " + ((bytes == null) ? 0 : bytes.length) + ", "); buffer.append("responseHeaders: " + nameValueListToJsMap(response.getResponseHeaders())); buffer.append("};\n"); appendToJSFile(buffer.toString()); } |
11
| Code Sample 1:
private String generateFilename() { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); try { digest.update(InetAddress.getLocalHost().toString().getBytes()); } catch (UnknownHostException e) { } digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(Runtime.getRuntime().freeMemory()).getBytes()); byte[] foo = new byte[128]; new SecureRandom().nextBytes(foo); digest.update(foo); hash = digest.digest(); } catch (NoSuchAlgorithmException e) { Debug.assrt(false); } return hexEncode(hash); }
Code Sample 2:
public static boolean verify(final String password, final String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } final byte[] data = Base64.decode(base64.toCharArray()); final byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); } |
11
| Code Sample 1:
public void copyFileToFileWithPaths(String sourcePath, String destinPath) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File file1 = new File(sourcePath); if (file1.exists() && (file1.isFile())) { File file2 = new File(destinPath); if (file2.exists()) { file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(sourcePath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(destinPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { throw new Exception("Source file not exist ! sourcePath = (" + sourcePath + ")"); } }
Code Sample 2:
protected void sendDoc(File indir, File outdir, File orig, Document doc, ServiceEndpoint ep) { ep.setMethod("simpleDocumentTransfer"); Document response = null; try { response = protocolHandler.sendMessage(ep, doc); } catch (TransportException e) { logger.warn("Message was not accepted, will try again later"); return; } String serial = String.valueOf(System.currentTimeMillis()); File origCopy = new File(outdir, orig.getName() + "." + serial); File respDrop = new File(outdir, orig.getName() + "." + serial + ".resp"); FileOutputStream respos = null; try { respos = new FileOutputStream(respDrop); serializeDocument(respos, response); } catch (IOException e) { logger.warn("Failed to dump response"); return; } finally { try { respos.close(); } catch (IOException ignored) { } } FileInputStream in = null; FileOutputStream out = null; byte[] buffer = new byte[2048]; try { in = new FileInputStream(orig); out = new FileOutputStream(origCopy); int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy original"); return; } finally { try { in.close(); out.close(); } catch (IOException ignored) { } } orig.delete(); logger.info("File processed: " + orig.getName()); } |
00
| Code Sample 1:
public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } }
Code Sample 2:
public void setTypeRefs(Connection conn) { log.traceln("\tProcessing " + table + " references.."); try { String query = " select distinct c.id, c.qualifiedname from " + table + ", CLASSTYPE c " + " where " + table + "." + reffield + " is null and " + table + "." + classnamefield + " = c.qualifiedname"; PreparedStatement pstmt = conn.prepareStatement(query); long start = new Date().getTime(); ResultSet rset = pstmt.executeQuery(); long queryTime = new Date().getTime() - start; log.debug("query time: " + queryTime + " ms"); String update = "update " + table + " set " + reffield + "=? where " + classnamefield + "=? and " + reffield + " is null"; PreparedStatement pstmt2 = conn.prepareStatement(update); int n = 0; start = new Date().getTime(); while (rset.next()) { n++; pstmt2.setInt(1, rset.getInt(1)); pstmt2.setString(2, rset.getString(2)); pstmt2.executeUpdate(); } queryTime = new Date().getTime() - start; log.debug("total update time: " + queryTime + " ms"); log.debug("number of times through loop: " + n); if (n > 0) log.debug("avg update time: " + (queryTime / n) + " ms"); pstmt2.close(); rset.close(); pstmt.close(); conn.commit(); log.verbose("Updated (committed) " + table + " references"); } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } } |
00
| Code Sample 1:
public static boolean isDicom(URL url) { assert url != null; boolean isDicom = false; BufferedInputStream is = null; try { is = new BufferedInputStream(url.openStream()); is.skip(DICOM_PREAMBLE_SIZE); byte[] buf = new byte[DICM.length]; is.read(buf); if (buf[0] == DICM[0] && buf[1] == DICM[1] && buf[2] == DICM[2] && buf[3] == DICM[3]) { isDicom = true; } } catch (Exception exc) { System.out.println("ImageFactory::isDicom(): exc=" + exc); } finally { if (is != null) { try { is.close(); } catch (Exception exc) { } } } return isDicom; }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } } |
11
| Code Sample 1:
public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
private boolean write(File file) { String filename = file.getPath(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteArrayOutputStream); try { StringBuffer xml = null; if (MainFrame.getInstance().getAnimation() != null) { MainFrame.getInstance().getAnimation().xml(out, "\t"); } else { xml = MainFrame.getInstance().getModel().xml("\t"); } if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(filename)); BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~")); char[] buffer = new char[65536]; int charsRead = 0; while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead); reader.close(); writer.close(); } BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n"); if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString()); writer.write("</jpatch>\n"); writer.close(); MainFrame.getInstance().getUndoManager().setChange(false); if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file); MainFrame.getInstance().setFilename(file.getName()); return true; } catch (IOException ioException) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE); return false; } } |
11
| Code Sample 1:
public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
Code Sample 2:
public static void copyFile(File source, File dest) throws Exception { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { throw new Exception("Cannot copy file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(), e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { throw new Exception("Cannot close streams.", e); } } } |
11
| Code Sample 1:
public static int getUrl(final String s) { try { final URL url = new URL(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); int count = 0; String data = null; while ((data = reader.readLine()) != null) { System.out.printf("Results(%3d) of data: %s\n", count, data); ++count; } return count; } catch (Exception ex) { throw new RuntimeException(ex); } }
Code Sample 2:
public Constructor run() throws Exception { String path = "META-INF/services/" + ComponentApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = ComponentApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (ComponentApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new ComponentApplicationException("No " + "ComponentApplicationContext implementation " + "found."); } |
11
| Code Sample 1:
private static String retrieveVersion(InputStream is) throws RepositoryException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { IOUtils.copy(is, buffer); } catch (IOException e) { throw new RepositoryException(exceptionLocalizer.format("device-repository-file-missing", DeviceRepositoryConstants.VERSION_FILENAME), e); } return buffer.toString().trim(); }
Code Sample 2:
private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); } |
11
| Code Sample 1:
public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); }
Code Sample 2:
public String getMarketInfo() { try { URL url = new URL("http://api.eve-central.com/api/evemon"); BufferedReader s = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String xml = ""; while ((line = s.readLine()) != null) { xml += line; } return xml; } catch (IOException ex) { ex.printStackTrace(); } return null; } |
11
| Code Sample 1:
private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; }
Code Sample 2:
public void run() { LOG.debug(this); String[] parts = createCmdArray(getCommand()); Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(parts); if (isBlocking()) { process.waitFor(); StringWriter out = new StringWriter(); IOUtils.copy(process.getInputStream(), out); String stdout = out.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stdout)) { LOG.info("Process stdout:\n" + stdout); } StringWriter err = new StringWriter(); IOUtils.copy(process.getErrorStream(), err); String stderr = err.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stderr)) { LOG.error("Process stderr:\n" + stderr); } } } catch (IOException ioe) { LOG.error(String.format("Could not exec [%s]", getCommand()), ioe); } catch (InterruptedException ie) { LOG.error(String.format("Interrupted [%s]", getCommand()), ie); } } |
00
| Code Sample 1:
public void saveDownloadFiles(List downloadFiles) throws SQLException { Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); Statement s = conn.createStatement(); s.executeUpdate("DELETE FROM DOWNLOADFILES"); s.close(); s = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO DOWNLOADFILES " + "(name,targetpath,size,fnkey,enabled,state,downloadaddedtime,downloadstartedtime,downloadfinishedtime," + "retries,lastdownloadstoptime,gqid,filelistfilesha) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (Iterator i = downloadFiles.iterator(); i.hasNext(); ) { FrostDownloadItem dlItem = (FrostDownloadItem) i.next(); int ix = 1; ps.setString(ix++, dlItem.getFilename()); ps.setString(ix++, dlItem.getTargetPath()); ps.setLong(ix++, (dlItem.getFileSize() == null ? 0 : dlItem.getFileSize().longValue())); ps.setString(ix++, dlItem.getKey()); ps.setBoolean(ix++, (dlItem.isEnabled() == null ? true : dlItem.isEnabled().booleanValue())); ps.setInt(ix++, dlItem.getState()); ps.setLong(ix++, dlItem.getDownloadAddedTime()); ps.setLong(ix++, dlItem.getDownloadStartedTime()); ps.setLong(ix++, dlItem.getDownloadFinishedTime()); ps.setInt(ix++, dlItem.getRetries()); ps.setLong(ix++, dlItem.getLastDownloadStopTime()); ps.setString(ix++, dlItem.getGqIdentifier()); ps.setString(ix++, dlItem.getFileListFileObject() == null ? null : dlItem.getFileListFileObject().getSha()); ps.executeUpdate(); } ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (Throwable t) { logger.log(Level.SEVERE, "Exception during save", t); try { conn.rollback(); } catch (Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); } try { conn.setAutoCommit(true); } catch (Throwable t1) { } } finally { AppLayerDatabase.getInstance().givePooledConnection(conn); } }
Code Sample 2:
public static void main(String[] args) throws Exception { final URL url = new URL("http://www.ebi.ac.uk/Tools/webservices/psicquic/registry/registry?action=ACTIVE&format=txt"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; Map<String, String> psiqcuicServices = new HashMap<String, String>(); while ((str = in.readLine()) != null) { final int idx = str.indexOf('='); psiqcuicServices.put(str.substring(0, idx), str.substring(idx + 1, str.length())); } in.close(); System.out.println("Found " + psiqcuicServices.size() + " active service(s)."); for (Object o : psiqcuicServices.keySet()) { String serviceName = (String) o; String serviceUrl = psiqcuicServices.get(serviceName); System.out.println(serviceName + " -> " + serviceUrl); UniversalPsicquicClient client = new UniversalPsicquicClient(serviceUrl); try { SearchResult<?> result = client.getByInteractor("brca2", 0, 50); System.out.println("Interactions found: " + result.getTotalCount()); for (BinaryInteraction binaryInteraction : result.getData()) { String interactorIdA = binaryInteraction.getInteractorA().getIdentifiers().iterator().next().getIdentifier(); String interactorIdB = binaryInteraction.getInteractorB().getIdentifiers().iterator().next().getIdentifier(); String interactionAc = "-"; if (!binaryInteraction.getInteractionAcs().isEmpty()) { CrossReference cr = (CrossReference) binaryInteraction.getInteractionAcs().iterator().next(); interactionAc = cr.getIdentifier(); } System.out.println("\tInteraction (" + interactionAc + "): " + interactorIdA + " interacts with " + interactorIdB); } } catch (Throwable e) { System.err.println("Service is down! " + serviceName + "(" + serviceUrl + ")"); } } } |
11
| Code Sample 1:
public static String encode(String arg) { if (arg == null) { arg = ""; } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(arg.getBytes(JavaCenterHome.JCH_CHARSET)); } catch (Exception e) { e.printStackTrace(); } return toHex(md5.digest()); }
Code Sample 2:
public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.exit(-1); } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } |
00
| Code Sample 1:
public boolean send(String number, String message) throws IOException { init(); message = message.substring(0, Math.min(MAX_PAYLOAD, message.length())); message = message.replace('\r', ' '); message = message.replace('\n', ' '); ActualFormParameters params = new ActualFormParameters(); String strippedNumber = strip(number); ActualFormParameter number1Param; ActualFormParameter number2Param; if (strippedNumber.startsWith("00")) strippedNumber = "+" + strippedNumber.substring(2); else if (strippedNumber.startsWith("0")) strippedNumber = "+49" + strippedNumber.substring(1); number1Param = new ActualFormParameter(number1InputElement.getName(), strippedNumber.substring(0, 6)); number2Param = new ActualFormParameter(number2InputElement.getName(), strippedNumber.substring(6)); params.add(number1Param); params.add(number2Param); ActualFormParameter messageParam = new ActualFormParameter(messageInputElement.getName(), message); params.add(messageParam); ActualFormParameter letterCountParam = new ActualFormParameter(letterCountInputElement.getName(), "" + (MAX_PAYLOAD - message.length())); params.add(letterCountParam); form.addDefaultParametersTo(params); Reader r = form.submitForm(params, form.getNetscapeRequestProperties()); String result = getStringFromReader(r); String pattern = "<meta http-equiv = \"refresh\" content=\"1; url="; int patternIndex = result.indexOf(pattern); if (patternIndex < 0) return false; int end = result.lastIndexOf("\">"); if (end < 0) return false; String url = result.substring(patternIndex + pattern.length(), end); result = getStringFromReader(new InputStreamReader(new URL(url).openStream())); return result.indexOf("wurde erfolgreich verschickt") >= 0; }
Code Sample 2:
public static void zip(String destination, String folder) { File fdir = new File(folder); File[] files = fdir.listFiles(); PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; FileInputStream in; byte[] data = new byte[1024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destination)); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < files.length; i++) { try { stdout.println(files[i].getName()); ZipEntry entry = new ZipEntry(files[i].getName()); in = new FileInputStream(files[i].getPath()); out.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.closeEntry(); in.close(); } catch (Exception e) { e.printStackTrace(); } } out.close(); } catch (IOException ex) { ex.printStackTrace(); } } |
11
| Code Sample 1:
public static synchronized String Encrypt(String plaintextPassword) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (Exception error) { throw new Exception(error.getMessage()); } try { md.update(plaintextPassword.getBytes("UTF-8")); } catch (Exception e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = String.valueOf(Base64Coder.encode(raw)); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; } |
00
| Code Sample 1:
public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
Code Sample 2:
protected Class findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (this.extensionJars != null) { for (int i = 0; i < this.extensionJars.length; i++) { JarFile extensionJar = this.extensionJars[i]; JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } } |
11
| Code Sample 1:
public int update(BusinessObject o) throws DAOException { int update = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ACCOUNT")); pst.setString(1, acc.getName()); pst.setString(2, acc.getAddress()); pst.setInt(3, acc.getCurrency()); pst.setInt(4, acc.getMainContact()); pst.setBoolean(5, acc.isArchived()); pst.setInt(6, acc.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; }
Code Sample 2:
private String AddAction(ResultSet node, String modo) throws SQLException { Connection cn = null; Connection cndef = null; String schema = boRepository.getDefaultSchemaName(boApplication.getDefaultApplication()).toLowerCase(); try { cn = this.getRepositoryConnection(p_ctx.getApplication(), p_ctx.getBoSession().getRepository().getName(), 1); cndef = this.getRepositoryConnection(p_ctx.getApplication(), p_ctx.getBoSession().getRepository().getName(), 2); String dml = null; String objecttype = node.getString("OBJECTTYPE"); if (objecttype.equalsIgnoreCase("T")) { boolean exists = existsTable(p_ctx, schema, node.getString("OBJECTNAME").toLowerCase()); String[] sysflds = { "SYS_USER", "SYS_ICN", "SYS_DTCREATE", "SYS_DTSAVE", "SYS_ORIGIN" }; String[] sysfdef = { "VARCHAR(25)", "NUMERIC(7)", "TIMESTAMP DEFAULT now()", "TIMESTAMP", "VARCHAR(30)" }; String[] sysftyp = { "C", "N", "D", "D", "C" }; String[] sysfsiz = { "25", "7", "", "", "30" }; String[] sysfndef = { "", "", "", "", "" }; String[] sysfdes = { "", "", "", "", "" }; if (!exists && !modo.equals("3")) { dml = "CREATE TABLE " + node.getString("OBJECTNAME") + " ("; for (int i = 0; i < sysflds.length; i++) { dml += (sysflds[i] + " " + sysfdef[i] + ((i < (sysflds.length - 1)) ? "," : ")")); } String vt = node.getString("OBJECTNAME"); if (node.getString("SCHEMA").equals("DEF")) { vt = "NGD_" + vt; } else if (node.getString("SCHEMA").equals("SYS")) { vt = "SYS_" + vt; } executeDDL(dml, node.getString("SCHEMA")); } if (modo.equals("3") && exists) { executeDDL("DROP TABLE " + node.getString("OBJECTNAME"), node.getString("SCHEMA")); CallableStatement call = cndef.prepareCall("DELETE FROM NGTDIC WHERE TABLENAME=?"); call.setString(1, node.getString("OBJECTNAME")); call.executeUpdate(); call.close(); } checkDicFields(node.getString("OBJECTNAME"), node.getString("SCHEMA"), sysflds, sysftyp, sysfsiz, sysfndef, sysfdes); } if (objecttype.equalsIgnoreCase("F")) { boolean fldchg = false; boolean fldexi = false; PreparedStatement pstm = cn.prepareStatement("select column_name,udt_name,character_maximum_length,numeric_precision,numeric_scale from information_schema.columns" + " where table_name=? and column_name=? and table_schema=?"); pstm.setString(1, node.getString("TABLENAME").toLowerCase()); pstm.setString(2, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(3, schema); ResultSet rslt = pstm.executeQuery(); if (rslt.next()) { int fieldsiz = rslt.getInt(3); int fielddec = rslt.getInt(5); if (",C,N,".indexOf("," + getNgtFieldTypeFromDDL(rslt.getString(2)) + ",") != -1) { if (getNgtFieldTypeFromDDL(rslt.getString(2)).equals("N")) { fieldsiz = rslt.getInt(4); } if (fielddec != 0) { if (!(fieldsiz + "," + fielddec).equals(node.getString("FIELDSIZE"))) { fldchg = true; } } else { if (!((fieldsiz == 0) && ((node.getString("FIELDSIZE") == null) || (node.getString("FIELDSIZE").length() == 0)))) { if (!("" + fieldsiz).equals(node.getString("FIELDSIZE"))) { fldchg = true; } } } } fldexi = true; } else { fldexi = false; } rslt.close(); pstm.close(); boolean drop = false; if (("20".indexOf(modo) != -1) && !fldexi) { dml = "ALTER TABLE " + node.getString("TABLENAME") + " add \"" + node.getString("OBJECTNAME").toLowerCase() + "\" "; } else if (("20".indexOf(modo) != -1) && fldexi && fldchg) { dml = "ALTER TABLE " + node.getString("TABLENAME") + " ALTER COLUMN \"" + node.getString("OBJECTNAME").toLowerCase() + "\" "; } else if (modo.equals("3") && fldexi) { dml = "ALTER TABLE " + node.getString("TABLENAME") + " drop COLUMN \"" + node.getString("OBJECTNAME").toLowerCase() + "\" "; String sql = "SELECT tc.constraint_name,tc.constraint_type" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name = ?" + " AND kcu.column_name = ?" + " and tc.table_schema=?"; PreparedStatement pstmrelc = cn.prepareStatement(sql); pstmrelc.setString(1, node.getString("TABLENAME").toLowerCase()); pstmrelc.setString(2, node.getString("OBJECTNAME").toLowerCase()); pstmrelc.setString(3, schema); ResultSet rsltrelc = pstmrelc.executeQuery(); while (rsltrelc.next()) { String constname = rsltrelc.getString(1); String consttype = rsltrelc.getString(2); PreparedStatement pstmdic = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? AND OBJECTTYPE=? AND OBJECTNAME=?"); pstmdic.setString(1, node.getString("TABLENAME")); pstmdic.setString(2, consttype.equals("R") ? "FK" : "PK"); pstmdic.setString(3, constname); int nrecs = pstmdic.executeUpdate(); pstm.close(); executeDDL("ALTER TABLE " + node.getString("TABLENAME") + " DROP CONSTRAINT " + constname, node.getString("SCHEMA")); } rsltrelc.close(); pstmrelc.close(); } if ((dml != null) && (dml.length() > 0) && !modo.equals("3")) { String mfield = node.getString("MACROFIELD"); if ((mfield != null) && !(!mfield.equals("TEXTOLIVRE") && !mfield.equals("NUMEROLIVRE") && !mfield.equals("TEXT") && !mfield.equals("BLOB") && !mfield.equals("MDATA"))) { String ngtft = ""; if (mfield.equals("TEXTOLIVRE")) { ngtft = "C"; } else if (mfield.equals("NUMEROLIVRE")) { ngtft = "N"; } else if (mfield.equals("RAW")) { ngtft = "RAW"; } else if (mfield.equals("TIMESTAMP")) { ngtft = "TIMESTAMP"; } else if (mfield.equals("MDATA")) { ngtft = "D"; } else if (mfield.equals("TEXT")) { ngtft = "CL"; } else if (mfield.equals("BLOB")) { ngtft = "BL"; } dml += getDDLFieldFromNGT(ngtft, node.getString("FIELDSIZE")); } else if ((mfield != null) && (mfield.length() > 0)) { dml += getMacrofieldDef(cndef, node.getString("MACROFIELD")); } else { dml += getDDLFieldFromNGT(node.getString("FIELDTYPE"), node.getString("FIELDSIZE")); } } String[] flds = new String[1]; flds[0] = node.getString("OBJECTNAME"); if (dml != null) { executeDDL(dml, node.getString("SCHEMA")); } } if (objecttype.equalsIgnoreCase("V")) { String viewText = null; PreparedStatement pstmrelc = cn.prepareStatement("SELECT view_definition FROM information_schema.views WHERE table_name=? " + "and table_schema=?"); pstmrelc.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstmrelc.setString(2, schema.toLowerCase()); ResultSet rsltrelc = pstmrelc.executeQuery(); boolean exists = false; if (rsltrelc.next()) { exists = true; viewText = rsltrelc.getString(1); viewText = viewText.substring(0, viewText.length() - 1); } rsltrelc.close(); pstmrelc.close(); if (!modo.equals("3")) { String vExpression = node.getString("EXPRESSION"); if (!vExpression.toLowerCase().equals(viewText)) { dml = "CREATE OR REPLACE VIEW \"" + node.getString("OBJECTNAME") + "\" AS \n" + vExpression; executeDDL(dml, node.getString("SCHEMA")); } } else { if (exists) { dml = "DROP VIEW " + node.getString("OBJECTNAME"); executeDDL(dml, node.getString("SCHEMA")); CallableStatement call = cndef.prepareCall("DELETE FROM NGTDIC WHERE TABLENAME=?"); call.setString(1, node.getString("OBJECTNAME")); call.executeUpdate(); call.close(); } } } if (objecttype.startsWith("PCK")) { String templatestr = node.getString("EXPRESSION"); String bstr = "/*begin_package*/"; String estr = "/*end_package*/"; if ("02".indexOf(modo) != -1) { if (templatestr.indexOf(bstr) != -1) { int defpos; dml = templatestr.substring(templatestr.indexOf(bstr), defpos = templatestr.indexOf(estr)); dml = "create or replace package " + node.getString("OBJECTNAME") + " is \n" + dml + "end " + node.getString("OBJECTNAME") + ";\n"; executeDDL(dml, node.getString("SCHEMA")); bstr = "/*begin_package_body*/"; estr = "/*end_package_body*/"; if (templatestr.indexOf(bstr, defpos) != -1) { dml = templatestr.substring(templatestr.indexOf(bstr, defpos), templatestr.indexOf(estr, defpos)); dml = "create or replace package body " + node.getString("OBJECTNAME") + " is \n" + dml + "end " + node.getString("OBJECTNAME") + ";\n"; executeDDL(dml, node.getString("SCHEMA")); } } else { } } } if (objecttype.startsWith("PK") || objecttype.startsWith("UN")) { String sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name = ?" + " AND tc.constraint_name = ?" + " and tc.table_schema=? order by ordinal_position"; PreparedStatement pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("TABLENAME").toLowerCase()); pstm.setString(2, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(3, schema.toLowerCase()); boolean isunique = objecttype.startsWith("UN"); ResultSet rslt = pstm.executeQuery(); boolean exists = false; StringBuffer expression = new StringBuffer(); while (rslt.next()) { if (exists) { expression.append(','); } exists = true; expression.append(rslt.getString(1)); } boolean diff = !expression.toString().toUpperCase().equals(node.getString("EXPRESSION")); rslt.close(); pstm.close(); if ((modo.equals("3") || diff) && exists) { sql = "SELECT tc.constraint_name,tc.table_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE ccu.constraint_name = ?" + " and tc.table_schema=?"; PreparedStatement pstmrefs = cn.prepareStatement(sql); pstmrefs.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstmrefs.setString(2, schema.toLowerCase()); ResultSet rsltrefs = pstmrefs.executeQuery(); while (rsltrefs.next()) { PreparedStatement pstmdelref = cndef.prepareStatement("DELETE NGTDIC WHERE OBJECTNAME=? AND SCHEMA=? AND TABLENAME=? AND OBJECTTYPE='FK'"); pstmdelref.setString(1, rsltrefs.getString(1)); pstmdelref.setString(2, node.getString("SCHEMA")); pstmdelref.setString(3, rsltrefs.getString(2)); pstmdelref.executeUpdate(); pstmdelref.close(); executeDDL("alter table " + rsltrefs.getString(2) + " drop constraint " + rsltrefs.getString(1), node.getString("SCHEMA")); } rsltrefs.close(); pstmrefs.close(); String insql = "'" + node.getString("EXPRESSION").toLowerCase().replaceAll(",", "\\',\\'") + "'"; sql = "SELECT tc.constraint_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name=? and " + "kcu.column_name in (" + insql + ")" + " and tc.table_schema=?"; pstmrefs = cn.prepareStatement(sql); pstmrefs.setString(1, node.getString("TABLENAME").toLowerCase()); pstmrefs.setString(2, schema.toLowerCase()); rsltrefs = pstmrefs.executeQuery(); while (rsltrefs.next()) { PreparedStatement pstmdelref = cndef.prepareStatement("DELETE NGTDIC WHERE OBJECTNAME=? AND SCHEMA=? AND TABLENAME=? AND OBJECTTYPE='FK'"); pstmdelref.setString(1, rsltrefs.getString(1)); pstmdelref.setString(2, node.getString("SCHEMA")); pstmdelref.setString(3, node.getString("TABLENAME")); pstmdelref.executeUpdate(); pstmdelref.close(); executeDDL("alter table " + node.getString("TABLENAME") + " drop constraint " + rsltrefs.getString(1), node.getString("SCHEMA")); } rsltrefs.close(); pstmrefs.close(); if (exists && diff) { dml = "alter table " + node.getString("TABLENAME") + " drop constraint " + node.getString("OBJECTNAME"); try { executeDDL(dml, node.getString("SCHEMA")); } catch (Exception e) { logger.warn(LoggerMessageLocalizer.getMessage("ERROR_EXCUTING_DDL") + " (" + dml + ") " + e.getMessage()); } } } if (!modo.equals("3") && (!exists || diff)) { if (isunique) { dml = "alter table " + node.getString("TABLENAME") + " add constraint " + node.getString("OBJECTNAME") + " unique (" + node.getString("EXPRESSION") + ")"; } else { dml = "alter table " + node.getString("TABLENAME") + " add primary key (" + node.getString("EXPRESSION") + ")"; } executeDDL(dml, node.getString("SCHEMA")); } } if (objecttype.startsWith("FK")) { String sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.constraint_name=?" + " and tc.table_name=?" + " and tc.table_schema=? order by ordinal_position"; PreparedStatement pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(2, node.getString("TABLENAME").toLowerCase()); pstm.setString(3, schema.toLowerCase()); ResultSet rslt = pstm.executeQuery(); boolean exists = false; String cExpress = ""; String express = node.getString("EXPRESSION"); if (rslt.next()) { exists = true; if (cExpress.length() > 0) cExpress += ","; cExpress += rslt.getString(1); } rslt.close(); pstm.close(); if (exists && !express.equals(cExpress)) { dml = "alter table " + node.getString("TABLENAME") + " drop constraint " + node.getString("OBJECTNAME"); executeDDL(dml, node.getString("SCHEMA")); } if (!modo.equals("3") && (!exists || !express.equals(cExpress))) { dml = "alter table " + node.getString("TABLENAME") + " add constraint " + node.getString("OBJECTNAME") + " foreign key (" + node.getString("EXPRESSION") + ") references " + node.getString("TABLEREFERENCE") + "(" + node.getString("FIELDREFERENCE") + ")"; executeDDL(dml, node.getString("SCHEMA")); } } if (objecttype.startsWith("IDX")) { boolean unflag = false; String sql = "SELECT n.nspname" + " FROM pg_catalog.pg_class c" + " JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid" + " JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid" + " LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner" + " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace" + " where c.relname=? and c.relkind='i' and n.nspname=?"; PreparedStatement pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(2, schema.toLowerCase()); ResultSet rslt = pstm.executeQuery(); boolean drop = false; boolean exists = false; boolean dbunflag = false; String oldexpression = ""; String newexpression = ""; if (rslt.next()) { exists = true; if ((unflag && !(dbunflag = rslt.getString(1).equals("UNIQUE")))) { drop = true; } rslt.close(); pstm.close(); sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.constraint_name=?" + " and tc.table_name=?" + " and tc.table_schema=? and tc.constraint_type='UNIQUE'"; pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(2, node.getString("TABLENAME").toLowerCase()); pstm.setString(3, schema.toLowerCase()); rslt = pstm.executeQuery(); while (rslt.next()) { oldexpression += (((oldexpression.length() > 0) ? "," : "") + rslt.getString(1)); } rslt.close(); pstm.close(); } else { rslt.close(); pstm.close(); } String aux = node.getString("EXPRESSION"); String[] nexo; if (aux != null) { nexo = node.getString("EXPRESSION").split(","); } else { nexo = new String[0]; } for (byte i = 0; i < nexo.length; i++) { newexpression += (((newexpression.length() > 0) ? "," : "") + ((nexo[i]).toUpperCase().trim())); } if (!drop) { drop = (!newexpression.equals(oldexpression)) && !oldexpression.equals(""); } if (exists && (drop || modo.equals("3"))) { if (!dbunflag) { dml = "DROP INDEX " + node.getString("OBJECTNAME"); } else { dml = "ALTER TABLE " + node.getString("TABLENAME") + " DROP CONSTRAINT " + node.getString("OBJECTNAME"); } executeDDL(dml, node.getString("SCHEMA")); exists = false; } if (!exists && !modo.equals("3")) { if (!node.getString("OBJECTNAME").equals("") && !newexpression.equals("")) { if (!unflag) { dml = "CREATE INDEX " + node.getString("OBJECTNAME") + " ON " + node.getString("TABLENAME") + "(" + newexpression + ")"; } else { dml = "ALTER TABLE " + node.getString("TABLENAME") + " ADD CONSTRAINT " + node.getString("OBJECTNAME") + " UNIQUE (" + newexpression + ")"; } executeDDL(dml, node.getString("SCHEMA")); } } } updateDictionaryTable(node, modo); return dml; } catch (SQLException e) { cn.rollback(); cndef.rollback(); throw (e); } finally { } } |
11
| Code Sample 1:
@Override public void execute() throws ProcessorExecutionException { try { if (getSource().getPaths() == null || getSource().getPaths().size() == 0 || getDestination().getPaths() == null || getDestination().getPaths().size() == 0) { throw new ProcessorExecutionException("No input and/or output paths specified."); } String temp_dir_prefix = getDestination().getPath().getParent().toString() + "/bcc_" + getDestination().getPath().getName() + "_"; SequenceTempDirMgr dirMgr = new SequenceTempDirMgr(temp_dir_prefix, context); dirMgr.setSeqNum(0); Path tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to AdjSetVertex"); Transformer transformer = new OutAdjVertex2AdjSetVertexTransformer(); transformer.setConf(context); transformer.setSrcPath(getSource().getPath()); tmpDir = dirMgr.getTempDir(); transformer.setDestPath(tmpDir); transformer.setMapperNum(getMapperNum()); transformer.setReducerNum(getReducerNum()); transformer.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to LabeledAdjSetVertex"); Vertex2LabeledTransformer l_transformer = new Vertex2LabeledTransformer(); l_transformer.setConf(context); l_transformer.setSrcPath(tmpDir); tmpDir = dirMgr.getTempDir(); l_transformer.setDestPath(tmpDir); l_transformer.setMapperNum(getMapperNum()); l_transformer.setReducerNum(getReducerNum()); l_transformer.setOutputValueClass(LabeledAdjSetVertex.class); l_transformer.execute(); Graph src; Graph dest; Path path_to_remember = tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": SpanningTreeRootChoose"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); GraphAlgorithm choose_root = new SpanningTreeRootChoose(); choose_root.setConf(context); choose_root.setSource(src); choose_root.setDestination(dest); choose_root.setMapperNum(getMapperNum()); choose_root.setReducerNum(getReducerNum()); choose_root.execute(); Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); String root_vertex_id = the_line.substring(SpanningTreeRootChoose.SPANNING_TREE_ROOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("++++++> Chosen the root of spanning tree = " + root_vertex_id); while (true) { System.out.println("++++++>" + dirMgr.getSeqNum() + " Generate the spanning tree rooted at : (" + root_vertex_id + ") from " + tmpDir); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); path_to_remember = tmpDir; GraphAlgorithm spanning = new SpanningTreeGenerate(); spanning.setConf(context); spanning.setSource(src); spanning.setDestination(dest); spanning.setMapperNum(getMapperNum()); spanning.setReducerNum(getReducerNum()); spanning.setParameter(ConstantLabels.ROOT_ID, root_vertex_id); spanning.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + " Test spanning convergence"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm conv_tester = new SpanningConvergenceTest(); conv_tester.setConf(context); conv_tester.setSource(src); conv_tester.setDestination(dest); conv_tester.setMapperNum(getMapperNum()); conv_tester.setReducerNum(getReducerNum()); conv_tester.execute(); long vertexes_out_of_tree = MRConsoleReader.getMapOutputRecordNum(conv_tester.getFinalStatus()); System.out.println("++++++> number of vertexes out of the spanning tree = " + vertexes_out_of_tree); if (vertexes_out_of_tree == 0) { break; } } System.out.println("++++++> From spanning tree to sets of edges"); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm tree2set = new Tree2EdgeSet(); tree2set.setConf(context); tree2set.setSource(src); tree2set.setDestination(dest); tree2set.setMapperNum(getMapperNum()); tree2set.setReducerNum(getReducerNum()); tree2set.execute(); long map_input_records_num = -1; long map_output_records_num = -2; Stack<Path> expanding_stack = new Stack<Path>(); do { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorJoin"); GraphAlgorithm minorjoin = new EdgeSetMinorJoin(); minorjoin.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorjoin.setSource(src); minorjoin.setDestination(dest); minorjoin.setMapperNum(getMapperNum()); minorjoin.setReducerNum(getReducerNum()); minorjoin.execute(); expanding_stack.push(tmpDir); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetJoin"); GraphAlgorithm join = new EdgeSetJoin(); join.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); join.setSource(src); join.setDestination(dest); join.setMapperNum(getMapperNum()); join.setReducerNum(getReducerNum()); join.execute(); map_input_records_num = MRConsoleReader.getMapInputRecordNum(join.getFinalStatus()); map_output_records_num = MRConsoleReader.getMapOutputRecordNum(join.getFinalStatus()); System.out.println("++++++> map in/out : " + map_input_records_num + "/" + map_output_records_num); } while (map_input_records_num != map_output_records_num); while (expanding_stack.size() > 0) { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetExpand"); GraphAlgorithm expand = new EdgeSetExpand(); expand.setConf(context); src = new Graph(Graph.defaultGraph()); src.addPath(expanding_stack.pop()); src.addPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); expand.setSource(src); expand.setDestination(dest); expand.setMapperNum(getMapperNum()); expand.setReducerNum(getReducerNum()); expand.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorExpand"); GraphAlgorithm minorexpand = new EdgeSetMinorExpand(); minorexpand.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorexpand.setSource(src); minorexpand.setDestination(dest); minorexpand.setMapperNum(getMapperNum()); minorexpand.setReducerNum(getReducerNum()); minorexpand.execute(); } System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetSummarize"); GraphAlgorithm summarize = new EdgeSetSummarize(); summarize.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); dest.setPath(getDestination().getPath()); summarize.setSource(src); summarize.setDestination(dest); summarize.setMapperNum(getMapperNum()); summarize.setReducerNum(getReducerNum()); summarize.execute(); dirMgr.deleteAll(); } catch (IOException e) { throw new ProcessorExecutionException(e); } catch (IllegalAccessException e) { throw new ProcessorExecutionException(e); } }
Code Sample 2:
@Override public LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; } |
11
| Code Sample 1:
public static void copyFile(File src, File dest) { try { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.err.println(ioe); } }
Code Sample 2:
public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map<String, String> _headers, Map<String, String> _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; _url = encodeURL(_url); HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams methodParams = ((HttpMethodBase) method).getParams(); if (methodParams == null) { methodParams = new HttpMethodParams(); ((HttpMethodBase) method).setParams(methodParams); } if (_timeout < 0) methodParams.setSoTimeout(0); else methodParams.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("Content-Type", _contentType); } if (_headers == null || !_headers.containsKey("User-Agent")) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("User-Agent", DEFAULT_USERAGENT); } if (_headers != null) { Iterator<Map.Entry<String, String>> iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator<Map.Entry<String, String>> iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); httpClient.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); InputStream instream = null; try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { LOG.warn("Http Satus:" + status + ",Url:" + _url); if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); } catch (IOException err) { LOG.error("Failed to access " + _url, err); throw err; } finally { IOUtils.closeQuietly(instream); if (method != null) method.releaseConnection(); } } |
00
| Code Sample 1:
public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); }
Code Sample 2:
protected void discoverRegistryEntries() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFactory.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormat.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); }
Code Sample 2:
public static String encrypt(String password) throws NoSuchAlgorithmException { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(password.getBytes()); byte[] cr = d.digest(); return getString(cr).toLowerCase(); } |
11
| Code Sample 1:
private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
Code Sample 2:
private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; } |
11
| Code Sample 1:
public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; }
Code Sample 2:
public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException { InputStream input = null; BufferedOutputStream bos = null; File tempUnit = null; try { URL url = null; int total = 0; try { url = new URL(urlStr); input = url.openStream(); URLConnection urlConnection; urlConnection = url.openConnection(); total = urlConnection.getContentLength(); } catch (IOException e) { throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e); } String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1); tempUnit = null; try { if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit"); File parent = tempUnit.getParentFile(); FileUtils.forceMkdir(parent); if (!tempUnit.exists()) FileUtils.touch(tempUnit); bos = new BufferedOutputStream(new FileOutputStream(tempUnit)); } catch (FileNotFoundException e) { throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (IOException e) { throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (DeployToolException e) { throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e); } logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr)); int size = -1; try { size = IOUtils.copy(input, bos); bos.flush(); } catch (IOException e) { logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit)); } if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr)); } finally { if (input != null) IOUtils.closeQuietly(input); if (bos != null) IOUtils.closeQuietly(bos); } logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath())); return tempUnit.getAbsolutePath(); } |
11
| Code Sample 1:
public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
Code Sample 2:
public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } if (!ftp.login(ftpUsername, ftpPassword)) { return null; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
Code Sample 2:
private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } } |
00
| Code Sample 1:
protected Drawing loadDrawing(ProgressIndicator progress) throws IOException { Drawing drawing = createDrawing(); if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { ((HttpURLConnection) uc).setUseCaches(false); } int contentLength = uc.getContentLength(); InputStream in = uc.getInputStream(); try { if (contentLength != -1) { in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); progress.setIndeterminate(false); } BufferedInputStream bin = new BufferedInputStream(in); bin.mark(512); IOException formatException = null; for (InputFormat format : drawing.getInputFormats()) { try { bin.reset(); } catch (IOException e) { uc = url.openConnection(); in = uc.getInputStream(); in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); bin = new BufferedInputStream(in); bin.mark(512); } try { bin.reset(); format.read(bin, drawing, true); formatException = null; break; } catch (IOException e) { formatException = e; } } if (formatException != null) { throw formatException; } } finally { in.close(); } } return drawing; }
Code Sample 2:
public GGMunicipalities getListMunicipalities() throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.geo.getListMunicipality")); qparams.add(new BasicNameValuePair("key", this.key)); String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGMunicipalities municipalities = JAXB.unmarshal(content, GGMunicipalities.class); return municipalities; } |
00
| Code Sample 1:
public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } }
Code Sample 2:
public static String uploadFile(String urlmsg, String path, String name) { try { System.out.println("Sending: " + urlmsg); URL url = new URL(urlmsg); if (url == null) { System.out.println("Resource " + urlmsg + " not found"); return null; } File outFile = new File(path, name); FileOutputStream out = new FileOutputStream(outFile); InputStream in = url.openStream(); byte[] buf = new byte[4 * 1024]; int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } out.close(); in.close(); return path + name; } catch (Exception e) { throw new GROBIDServiceException("An exception occured while running Grobid.", e); } } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&") != -1) { String syn1 = syn.substring(0, syn.indexOf("&")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } } |
11
| Code Sample 1:
private void getRandomGUID(boolean secure) throws NoSuchAlgorithmException { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); throw e; } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } } |
00
| Code Sample 1:
public void bubblesort(String filenames[]) { for (int i = filenames.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { String temp; if (filenames[j].compareTo(filenames[j + 1]) > 0) { temp = filenames[j]; filenames[j] = filenames[j + 1]; filenames[j + 1] = temp; } } } }
Code Sample 2:
public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); } |
00
| Code Sample 1:
public void doUpdateByIP() throws Exception { if (!isValidate()) { throw new CesSystemException("User_session.doUpdateByIP(): Illegal data values for update"); } Connection con = null; PreparedStatement ps = null; String strQuery = "UPDATE " + Common.USER_SESSION_TABLE + " SET " + "session_id = ?, user_id = ?, begin_date = ? , " + " mac_no = ?, login_id= ? " + "WHERE ip_address = ?"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strQuery); ps.setString(1, this.sessionID); ps.setInt(2, this.user.getUserID()); ps.setTimestamp(3, this.beginDate); ps.setString(4, this.macNO); ps.setString(5, this.loginID); ps.setString(6, this.ipAddress); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("User_session.doUpdateByIP(): ERROR updating data in T_SYS_USER_SESSION!! " + "resultCount = " + resultCount); } con.commit(); } catch (SQLException se) { if (con != null) { con.rollback(); } throw new CesSystemException("User_session.doUpdateByIP(): SQLException while updating user_session; " + "session_id = " + this.sessionID + " :\n\t" + se); } finally { con.setAutoCommit(true); closePreparedStatement(ps); closeConnection(dbo); } }
Code Sample 2:
public void sortingByBubble(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } |
11
| Code Sample 1:
private static final void cloneFile(File origin, File target) throws IOException { FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(origin).getChannel(); destChannel = new FileOutputStream(target).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) srcChannel.close(); if (destChannel != null) destChannel.close(); } }
Code Sample 2:
private static boolean computeMovieAverages(String completePath, String MovieAveragesOutputFileName, String MovieIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TShortObjectHashMap MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalMovies = MovieLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CustomerRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); short[] itr = MovieLimitsTHash.keys(); Arrays.sort(itr); ByteBuffer buf; for (i = 0; i < totalMovies; i++) { short currentMovie = itr[i]; a = (TIntArrayList) MovieLimitsTHash.get(currentMovie); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 5); inC.read(buf, (startIndex - 1) * 5); } else { buf = ByteBuffer.allocate(5); inC.read(buf, (startIndex - 1) * 5); } buf.flip(); int bufsize = buf.capacity() / 5; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getInt(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(6); outbuf.putShort(currentMovie); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } |
11
| Code Sample 1:
public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } }
Code Sample 2:
public static String calculatesMD5(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } return hexString.toString(); } |
11
| Code Sample 1:
public static void copy(File in, File out) throws IOException { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
Code Sample 2:
public static void copy(FileInputStream in, File destination) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = in.getChannel(); dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } } |
00
| Code Sample 1:
public String[] retrieveFasta(String id) throws Exception { URL url = new URL("http://www.ebi.ac.uk/ena/data/view/" + id + "&display=fasta"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String header = reader.readLine(); StringBuffer seq = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { seq.append(line); } reader.close(); return new String[] { header, seq.toString() }; }
Code Sample 2:
private void addDocToDB(String action, DataSource database) { String typeOfDoc = findTypeOfDoc(action).trim().toLowerCase(); Connection con = null; try { con = database.getConnection(); con.setAutoCommit(false); checkDupDoc(typeOfDoc, con); String add = "insert into " + typeOfDoc + " values( ?, ?, ?, ?, ?, ?, ? )"; PreparedStatement prepStatement = con.prepareStatement(add); prepStatement.setString(1, selectedCourse.getCourseId()); prepStatement.setString(2, selectedCourse.getAdmin()); prepStatement.setTimestamp(3, getTimeStamp()); prepStatement.setString(4, getLink()); prepStatement.setString(5, homePage.getUser()); prepStatement.setString(6, getText()); prepStatement.setString(7, getTitle()); prepStatement.executeUpdate(); prepStatement.close(); con.commit(); } catch (Exception e) { sqlError = true; e.printStackTrace(); if (con != null) try { con.rollback(); } catch (Exception logOrIgnore) { } try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } finally { if (con != null) try { con.close(); } catch (Exception logOrIgnore) { } } } |
11
| Code Sample 1:
private void copyFile(String fileName, String messageID, boolean isError) { try { File inputFile = new File(fileName); File outputFile = null; if (isError) { outputFile = new File(provider.getErrorDataLocation(folderName) + messageID + ".xml"); } else { outputFile = new File(provider.getDataProcessedLocation(folderName) + messageID + ".xml"); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; } |
00
| Code Sample 1:
public void read(Model m, String url) throws JenaException { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) read(m, conn.getInputStream(), url); else read(m, new InputStreamReader(conn.getInputStream(), encoding), url); } catch (FileNotFoundException e) { throw new DoesNotExistException(url); } catch (IOException e) { throw new JenaException(e); } }
Code Sample 2:
public void processSaveHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_HOLDING " + "SET " + " full_name_HOLDING=?, " + " NAME_HOLDING=? " + "WHERE ID_HOLDING = ? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); RsetTools.setLong(ps, num++, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); processInsertRelatedCompany(dbDyn, holdingBean, authSession); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } |
00
| Code Sample 1:
public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) res += "0" + tmp; else res += tmp; } } catch (NoSuchAlgorithmException ex) { } return res; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
Code Sample 2:
public static PortalConfig install(File xml, File dir) throws IOException, ConfigurationException { if (!dir.exists()) { log.info("Creating directory {}", dir); dir.mkdirs(); } if (!xml.exists()) { log.info("Installing default configuration to {}", xml); OutputStream output = new FileOutputStream(xml); try { InputStream input = ResourceLoader.open("res://" + PORTAL_CONFIG_XML); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { output.close(); } } return create(xml, dir); } |
00
| Code Sample 1:
public void delete(String fileName) throws IOException { log.debug("deleting: " + fileName); URL url = new URL(this.endpointURL + "?operation=delete&filename=" + fileName); URLConnection connection = url.openConnection(); connection.setDoOutput(false); connection.setDoInput(true); connection.setUseCaches(false); connection.getInputStream(); }
Code Sample 2:
public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; } |
00
| Code Sample 1:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
Code Sample 2:
@Test public void testWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } |
00
| Code Sample 1:
public static void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void messageDigestTest() { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("computer".getBytes()); md.update("networks".getBytes()); System.out.println(new String(md.digest())); System.out.println(new String(md.digest("computernetworks".getBytes()))); } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; } |
00
| Code Sample 1:
@Nullable @Override public InputSource resolveEntity(final String publicId, final String systemId) throws IOException { if (systemId.endsWith(".xml")) { return null; } InputSource inputSource = null; final URL url = IOUtils.getResource(new File("system/dtd"), PATTERN_DIRECTORY_PART.matcher(systemId).replaceAll("")); final InputStream inputStream = url.openStream(); try { final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); try { inputSource = new InputSource(bufferedInputStream); } finally { if (inputSource == null) { bufferedInputStream.close(); } } } finally { if (inputSource == null) { inputStream.close(); } } return inputSource; }
Code Sample 2:
public boolean run() { Connection conn = null; Statement stmt = null; try { conn = getDataSource().getConnection(); conn.setAutoCommit(false); conn.rollback(); stmt = conn.createStatement(); for (String task : tasks) { if (task.length() == 0) continue; LOGGER.info("Executing SQL migration: " + task); stmt.executeUpdate(task); } conn.commit(); } catch (SQLException ex) { try { conn.rollback(); } catch (Throwable th) { } throw new SystemException("Cannot execute SQL migration", ex); } finally { try { if (stmt != null) stmt.close(); } catch (Throwable th) { LOGGER.error(th); } try { if (stmt != null) conn.close(); } catch (Throwable th) { LOGGER.error(th); } } return true; } |
11
| Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
static boolean writeProperties(Map<String, String> customProps, File destination) throws IOException { synchronized (PropertiesIO.class) { L.info(Msg.msg("PropertiesIO.writeProperties.start")); File tempFile = null; BufferedInputStream existingCfgInStream = null; FileInputStream in = null; FileOutputStream out = null; PrintStream ps = null; FileChannel fromChannel = null, toChannel = null; String line = null; try { existingCfgInStream = new BufferedInputStream(destination.exists() ? new FileInputStream(destination) : defaultPropertiesStream()); tempFile = File.createTempFile("properties-", ".tmp", null); ps = new PrintStream(tempFile); while ((line = Utils.readLine(existingCfgInStream)) != null) { String lineReady2write = setupLine(line, customProps); ps.println(lineReady2write); } destination.getParentFile().mkdirs(); in = new FileInputStream(tempFile); out = new FileOutputStream(destination, false); fromChannel = in.getChannel(); toChannel = out.getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); L.info(Msg.msg("PropertiesIO.writeProperties.done").replace("#file#", destination.getAbsolutePath())); return true; } finally { if (existingCfgInStream != null) existingCfgInStream.close(); if (ps != null) ps.close(); if (fromChannel != null) fromChannel.close(); if (toChannel != null) toChannel.close(); if (out != null) out.close(); if (in != null) in.close(); if (tempFile != null && tempFile.exists()) tempFile.delete(); } } } |
00
| Code Sample 1:
private void copy(String url, File toDir) throws IOException { System.err.println("url=" + url + " dir=" + toDir); if (url.endsWith("/")) { String basename = url.substring(url.lastIndexOf("/", url.length() - 2) + 1); File directory = new File(toDir, basename); directory.mkdir(); LineNumberReader reader = new LineNumberReader(new InputStreamReader(new URL(url).openStream(), "utf-8")); String line; while ((line = reader.readLine()) != null) { System.err.println(line.replace('\t', '|')); int tab = line.lastIndexOf('\t', line.lastIndexOf('\t', line.lastIndexOf('\t') - 1) - 1); System.err.println(tab); char type = line.charAt(tab + 1); String file = line.substring(0, tab); copy(url + URIUtil.encodePath(file) + (type == 'd' ? "/" : ""), directory); } } else { String basename = url.substring(url.lastIndexOf("/") + 1); File file = new File(toDir, basename); System.err.println("copy " + url + " --> " + file); IO.copy(new URL(url).openStream(), new FileOutputStream(file)); } }
Code Sample 2:
private void getPicture(String urlPath, String picId) throws Exception { URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); byte[] data = readStream(inputStream); File file = new File(picDirectory + picId); FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(data); outputStream.close(); } conn.disconnect(); } |
11
| Code Sample 1:
private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException { if (source == null) throw new NullPointerException("Parameter 'source' is null"); if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath()); if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath()); File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size())); if (newLocation.compareTo(source) != 0) { switch(type) { case MOVE: source.renameTo(newLocation); break; case COPY: FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(newLocation).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); break; } } Frame f = new Frame(newLocation); f.createThumbNail(); frames_.add(f); return f; }
Code Sample 2:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { log.fatal("not a http request"); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int pathStartIdx = 0; String resourceName = null; pathStartIdx = uri.indexOf(path); if (pathStartIdx <= -1) { log.fatal("the url pattern must match: " + path + " found uri: " + uri); return; } resourceName = uri.substring(pathStartIdx + path.length()); int suffixIdx = uri.lastIndexOf('.'); if (suffixIdx <= -1) { log.fatal("no file suffix found for resource: " + uri); return; } String suffix = uri.substring(suffixIdx + 1).toLowerCase(); String mimeType = (String) mimeTypes.get(suffix); if (mimeType == null) { log.fatal("no mimeType found for resource: " + uri); log.fatal("valid mimeTypes are: " + mimeTypes.keySet()); return; } String themeName = getThemeName(); if (themeName == null) { themeName = this.themeName; } if (!themeName.startsWith("/")) { themeName = "/" + themeName; } InputStream is = null; is = ResourceFilter.class.getResourceAsStream(themeName + resourceName); if (is != null) { IOUtils.copy(is, response.getOutputStream()); response.setContentType(mimeType); response.flushBuffer(); IOUtils.closeQuietly(response.getOutputStream()); IOUtils.closeQuietly(is); } else { log.fatal("error loading resource: " + resourceName); } } |
11
| Code Sample 1:
private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
11
| Code Sample 1:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
Code Sample 2:
public static long removePropertyInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, String propriete) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (propriete.equals(Metadata.TITLE)) { coreProperties.setTitle(""); } else if (propriete.equals(Metadata.AUTHOR)) { coreProperties.setCreator(""); } else if (propriete.equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(""); } else if (propriete.equals(Metadata.COMMENTS)) { coreProperties.setDescription(""); } else if (propriete.equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(""); } else if (propriete.equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(""); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(propriete)) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(propriete)) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } } |
11
| Code Sample 1:
void copyFile(File inputFile, File outputFile) { try { FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private static void zip(File d) throws FileNotFoundException, IOException { String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(d.getParent() + File.separator + "dist.zip"))); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); int skipl = d.getCanonicalPath().length(); ZipEntry entry = new ZipEntry(f.getPath().substring(skipl)); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); FileUtils.moveFile(new File(d.getParent() + File.separator + "dist.zip"), new File(d + File.separator + "dist.zip")); } |
11
| Code Sample 1:
private void copyIntoFile(String resource, File output) throws IOException { FileOutputStream out = null; InputStream in = null; try { out = FileUtils.openOutputStream(output); in = GroovyInstanceTest.class.getResourceAsStream(resource); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }
Code Sample 2:
public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } } |
11
| Code Sample 1:
private void copy(String imgPath, String path) { try { File input = new File(imgPath); File output = new File(path, input.getName()); if (output.exists()) { if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return; } byte[] data = new byte[1024]; FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); int length; while ((length = bis.read(data)) > 0) { bos.write(data, 0, length); bos.flush(); } bos.close(); fis.close(); IJavaProject ijp = VisualSwingPlugin.getCurrentProject(); if (ijp != null) { ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); view.refresh(); view.expandAll(); } } catch (Exception e) { VisualSwingPlugin.getLogger().error(e); } }
Code Sample 2:
public static boolean copyFile(File src, File des) { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(des)); int b; while ((b = in.read()) != -1) out.write(b); out.flush(); out.close(); in.close(); return true; } catch (IOException ie) { m_logCat.error("Copy file + " + src + " to " + des + " failed!", ie); return false; } } |
11
| Code Sample 1:
@Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } }
Code Sample 2:
public Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; } |
00
| Code Sample 1:
protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); }
Code Sample 2:
public char[] getDataAsCharArray(String url) { try { char[] dat = null; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStream is = urlc.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset())); int len = urlc.getContentLength(); dat = new char[len]; int i = 0; int c; while ((c = reader.read()) != -1) { char character = (char) c; dat[i] = character; i++; } is.close(); return dat; } catch (Exception e) { throw new RuntimeException(e); } } |
00
| Code Sample 1:
public URLStream(URL url) throws IOException { this.url = url; this.conn = this.url.openConnection(); contentType = conn.getContentType(); name = url.toExternalForm(); size = new Long(conn.getContentLength()); sourceInfo = "url"; }
Code Sample 2:
@Test public void pk() throws Exception { Connection conn = s.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into t_test(t_name,t_cname,t_data,t_date,t_double) values(?,?,?,?,?)"); for (int i = 10; i < 20; ++i) { ps.setString(1, "name-" + i); ps.setString(2, "cname-" + i); ps.setBlob(3, null); ps.setTimestamp(4, new Timestamp(System.currentTimeMillis())); ps.setNull(5, java.sql.Types.DOUBLE); ps.executeUpdate(); } conn.rollback(); conn.setAutoCommit(true); ps.close(); conn.close(); } |
00
| Code Sample 1:
public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.decrypt(reader, writer, key, mode); }
Code Sample 2:
private void announce(String trackerURL, byte[] hash, byte[] peerId, int port) { try { String strUrl = trackerURL + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&peer_id=" + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&port=" + port + "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1"; URL url = new URL(strUrl); URLConnection con = url.openConnection(); con.connect(); con.getContent(); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
protected List webservice(URL url, List locations, boolean followRedirect) throws GeoServiceException { long start = System.currentTimeMillis(); int rowCount = 0, hitCount = 0; try { HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); try { con.getClass().getMethod("setConnectTimeout", new Class[] { Integer.TYPE }).invoke(con, new Object[] { TIMEOUT }); } catch (Throwable t) { LOG.info("can't set connection timeout"); } con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); Writer out = new OutputStreamWriter(con.getOutputStream(), UTF8); out.write(HEADER + "\n"); for (int i = 0; i < locations.size(); i++) { if (i > 0) out.write("\n"); out.write(encode((GeoLocation) locations.get(i))); } out.close(); } catch (IOException e) { throw new GeoServiceException("Accessing GEO Webservice failed", e); } List rows = new ArrayList(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), UTF8)); for (int l = 0; l < locations.size(); l++) { String line = in.readLine(); LOG.finer(line); if (line == null) break; if (l == 0 && followRedirect) { try { return webservice(new URL(line), locations, false); } catch (MalformedURLException e) { } } rowCount++; List row = new ArrayList(); if (!line.startsWith("?")) { StringTokenizer hits = new StringTokenizer(line, ";"); while (hits.hasMoreTokens()) { GeoLocation hit = decode(hits.nextToken()); if (hit != null) { row.add(hit); hitCount++; } } } rows.add(row); } in.close(); } catch (IOException e) { throw new GeoServiceException("Reading from GEO Webservice failed", e); } if (rows.size() < locations.size()) throw new GeoServiceException("GEO Webservice returned " + rows.size() + " rows for " + locations.size() + " locations"); return rows; } finally { long secs = (System.currentTimeMillis() - start) / 1000; LOG.fine("query for " + locations.size() + " locations in " + secs + "s resulted in " + rowCount + " rows and " + hitCount + " total hits"); } }
Code Sample 2:
private void encryptChkFile(ProjectMember member, File chkFile) throws Exception { final java.io.FileReader reader = new java.io.FileReader(chkFile); final File encryptedChkFile = new File(member.createOutputFileName(outputPath, "chk")); FileOutputStream outfile = null; ObjectOutputStream outstream = null; Utilities.discardBooleanResult(encryptedChkFile.getParentFile().mkdirs()); outfile = new FileOutputStream(encryptedChkFile); outstream = new ObjectOutputStream(outfile); outstream.writeObject(new Format().parse(reader)); reader.close(); outfile.close(); outstream.close(); } |
00
| Code Sample 1:
public boolean actualizarIdPartida(int idJugadorDiv, int idRonda, int idPartida) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
Code Sample 2:
public static byte[] createAuthenticator(ByteBuffer data, String secret) { assert data.isDirect() == false : "must not a direct ByteBuffer"; int pos = data.position(); if (pos < RadiusPacket.MIN_PACKET_LENGTH) { System.err.println("packet too small"); return null; } try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] arr = data.array(); md5.reset(); md5.update(arr, 0, pos); md5.update(secret.getBytes()); return md5.digest(); } catch (NoSuchAlgorithmException nsaex) { throw new RuntimeException("Could not access MD5 algorithm, fatal error"); } } |
11
| Code Sample 1:
public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } |
00
| Code Sample 1:
private void initStreams() throws IOException { if (audio != null) { audio.close(); } if (url != null) { audio = new OggInputStream(url.openStream()); } else { audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); } }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } |
00
| Code Sample 1:
public List<Template> getTemplatesByKeywordsAndPage(String keywords, int page) { String newKeywords = keywords; if (keywords == null || keywords.trim().length() == 0) { newKeywords = TemplateService.NO_KEYWORDS; } List<Template> templates = new ArrayList<Template>(); String restURL = configuration.getBeehiveRESTRootUrl() + "templates/keywords/" + newKeywords + "/page/" + page; HttpGet httpGet = new HttpGet(restURL); httpGet.setHeader("Accept", "application/json"); this.addAuthentication(httpGet); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) { throw new NotAuthenticatedException("User " + userService.getCurrentUser().getUsername() + " not authenticated! "); } throw new BeehiveNotAvailableException("Beehive is not available right now! "); } InputStreamReader reader = new InputStreamReader(response.getEntity().getContent()); BufferedReader buffReader = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = buffReader.readLine()) != null) { sb.append(line); sb.append("\n"); } String result = sb.toString(); TemplateList templateList = buildTemplateListFromJson(result); List<TemplateDTO> dtoes = templateList.getTemplates(); for (TemplateDTO dto : dtoes) { templates.add(dto.toTemplate()); } } catch (IOException e) { throw new BeehiveNotAvailableException("Failed to get template list, The beehive is not available right now ", e); } return templates; }
Code Sample 2:
@SuppressWarnings("deprecation") public static final ReturnCode runCommand(IOBundle io, String[] args) { if ((args.length < 3) || (args.length > 4)) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 3) && (!args[1].equals("show"))) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 4) && (!(args[2].equals("training") || args[2].equals("log") || args[2].equals("configuration")))) return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Access denied to directory: " + args[2]); if (args[1].equals("open")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); io.println(fileName); io.println(file.length() + " bytes"); while (dis.available() != 0) { io.println(dis.readLine()); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_NOT_FOUND, "File " + fileName + " doesn't exist"); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error reading File " + fileName); } } else if (args[1].equals("save")) { final String fileName = args[2] + "/" + args[3]; String line; try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); line = io.readLine(); int count = Integer.parseInt(line.trim()); while (count > 0) { out.write(io.read()); count = count - 1; } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error writing File " + fileName); } } else if (args[1].equals("delete")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); if (!file.exists()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such file or directory: " + fileName); if (!file.canWrite()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "File is write-protected: " + fileName); if (file.isDirectory()) { String[] files = file.list(); if (files.length > 0) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Directory is not empty: " + fileName); } if (!file.delete()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Deletion failed: " + fileName); } else if (args[1].equals("show")) { File directory = new File(args[2]); String[] files; if ((!directory.isDirectory()) || (!directory.exists())) { return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such directory: " + directory); } int count = 0; files = directory.list(); io.println("Files in directory \"" + directory + "\":"); for (int i = 0; i < files.length; i++) { directory = new File(files[i]); if (!directory.isDirectory()) { count++; io.println(" " + files[i]); } } io.println("Total " + count + " files"); } else return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Unrecognized command"); return ReturnCode.makeReturnCode(ReturnCode.RET_OK); } |
11
| Code Sample 1:
public String sendRequestHTTPTunelling(java.lang.String servletName, java.lang.String request) { String reqxml = ""; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); String req1xml = request; java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println(req1xml); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("log.txt"); pw.write(req1xml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8"); retdoc = (new org.jdom.input.SAXBuilder()).build(br); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("log3.txt"); pw.write(reqxml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(System.out); javax.swing.JOptionPane.showMessageDialog(null, "<html>Could not establish connection with the server, <br>Please verify server name/IP adress, <br>Also check if NewGenLib server is running</html>", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE); } System.out.println(reqxml); return (new org.jdom.output.XMLOutputter()).outputString(retdoc); }
Code Sample 2:
private static List lookupForImplementations(final Class clazz, final ClassLoader loader, final String[] defaultImplementations, final boolean onlyFirst, final boolean returnInstances) throws ClassNotFoundException { if (clazz == null) { throw new IllegalArgumentException("Argument 'clazz' cannot be null!"); } ClassLoader classLoader = loader; if (classLoader == null) { classLoader = clazz.getClassLoader(); } String interfaceName = clazz.getName(); ArrayList tmp = new ArrayList(); ArrayList toRemove = new ArrayList(); String className = System.getProperty(interfaceName); if (className != null && className.trim().length() > 0) { tmp.add(className.trim()); } Enumeration en = null; try { en = classLoader.getResources("META-INF/services/" + clazz.getName()); } catch (IOException e) { e.printStackTrace(); } while (en != null && en.hasMoreElements()) { URL url = (URL) en.nextElement(); InputStream is = null; try { is = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; do { line = reader.readLine(); boolean remove = false; if (line != null) { if (line.startsWith("#-")) { remove = true; line = line.substring(2); } int pos = line.indexOf('#'); if (pos >= 0) { line = line.substring(0, pos); } line = line.trim(); if (line.length() > 0) { if (remove) { toRemove.add(line); } else { tmp.add(line); } } } } while (line != null); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } if (defaultImplementations != null) { for (int i = 0; i < defaultImplementations.length; i++) { tmp.add(defaultImplementations[i].trim()); } } if (!clazz.isInterface()) { int m = clazz.getModifiers(); if (!Modifier.isAbstract(m) && Modifier.isPublic(m) && !Modifier.isStatic(m)) { tmp.add(interfaceName); } } tmp.removeAll(toRemove); ArrayList res = new ArrayList(); for (Iterator it = tmp.iterator(); it.hasNext(); ) { className = (String) it.next(); try { Class c = Class.forName(className, false, classLoader); if (c != null) { if (clazz.isAssignableFrom(c)) { if (returnInstances) { Object o = null; try { o = c.newInstance(); } catch (Throwable e) { e.printStackTrace(); } if (o != null) { res.add(o); if (onlyFirst) { return res; } } } else { res.add(c); if (onlyFirst) { return res; } } } else { logger.warning("MetaInfLookup: Class '" + className + "' is not a subclass of class : " + interfaceName); } } } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Cannot create implementation of interface: " + interfaceName, e); } } if (res.size() == 0) { throw new ClassNotFoundException("Cannot find any implemnetation of class " + interfaceName); } return res; } |
00
| Code Sample 1:
public static void main(String[] args) { try { { byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1)); System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1)); byte[] dbytes = decode(encodeBytes(bytes1)); System.out.print(encodeBytes(bytes1) + " decoded: "); for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n")); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); byte[] bytes = new byte[0]; int b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, temp, 0, bytes.length); temp[bytes.length] = (byte) b; bytes = temp; } b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); fos.write(bytes); fos.close(); fis = new java.io.FileInputStream("test.gif_out"); b64is = new Base64.InputStream(fis, ENCODE); byte[] ebytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[ebytes.length + 1]; System.arraycopy(ebytes, 0, temp, 0, ebytes.length); temp[ebytes.length] = (byte) b; ebytes = temp; } b64is.close(); String s = new String(ebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif_out"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif.b64_out"); fos.write(ebytes); fis = new java.io.FileInputStream("test.gif.b64_out"); b64is = new Base64.InputStream(fis, DECODE); byte[] edbytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[edbytes.length + 1]; System.arraycopy(edbytes, 0, temp, 0, edbytes.length); temp[edbytes.length] = (byte) b; edbytes = temp; } b64is.close(); iicon = new javax.swing.ImageIcon(edbytes); jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); byte[] rbytes = new byte[0]; int b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rbytes.length + 1]; System.arraycopy(rbytes, 0, temp, 0, rbytes.length); temp[rbytes.length] = (byte) b; rbytes = temp; } fis.close(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE); b64os.write(rbytes); b64os.close(); fis = new java.io.FileInputStream("test.gif.b64_out2"); byte[] rebytes = new byte[0]; b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rebytes.length + 1]; System.arraycopy(rebytes, 0, temp, 0, rebytes.length); temp[rebytes.length] = (byte) b; rebytes = temp; } fis.close(); String s = new String(rebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif.b64_out2"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream(fos, DECODE); b64os.write(rebytes); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while ((b = b64is.read()) >= 0) fos.write(b); fos.close(); b64is.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
protected InputStream callApiMethod(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createBingSearchApiClientException(error); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingSearchException(e); } } |
00
| Code Sample 1:
public static Bitmap loadPhotoBitmap(final String imageUrl, final String type) { InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; }
Code Sample 2:
private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } } |
11
| Code Sample 1:
protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } }
Code Sample 2:
protected void copyFile(File sourceFile, File destFile) { FileChannel in = null; FileChannel out = null; try { if (!verifyOrCreateParentPath(destFile.getParentFile())) { throw new IOException("Parent directory path " + destFile.getAbsolutePath() + " did not exist and could not be created"); } if (destFile.exists() || destFile.createNewFile()) { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } else { throw new IOException("Couldn't create file for " + destFile.getAbsolutePath()); } } catch (IOException ioe) { if (destFile.exists() && destFile.length() < sourceFile.length()) { destFile.delete(); } ioe.printStackTrace(); } finally { try { in.close(); } catch (Throwable t) { } try { out.close(); } catch (Throwable t) { } destFile.setLastModified(sourceFile.lastModified()); } } |
00
| Code Sample 1:
public void writeToStream(String urlString, OutputStream os) { BufferedInputStream input = null; try { URL url = new URL(urlString); System.out.println("Opening stream:" + url.toString()); input = new BufferedInputStream(url.openStream(), 4 * 1024 * 1024); byte[] data = new byte[102400]; int read; while ((read = input.read(data)) != -1) { os.write(data, 0, read); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
public static int deleteSysPosInsert() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_SYS_POSITION_INSERT "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; } |
11
| Code Sample 1:
static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } }
Code Sample 2:
private void documentFileChooserActionPerformed(java.awt.event.ActionEvent evt) { if (evt.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { File selectedFile = documentFileChooser.getSelectedFile(); File collectionCopyFile; String newDocumentName = selectedFile.getName(); Document newDocument = new Document(newDocumentName); if (activeCollection.containsDocument(newDocument)) { int matchingFilenameDistinguisher = 1; StringBuilder distinguisherReplacer = new StringBuilder(); newDocumentName = newDocumentName.concat("(" + matchingFilenameDistinguisher + ")"); newDocument.setDocumentName(newDocumentName); while (activeCollection.containsDocument(newDocument)) { matchingFilenameDistinguisher++; newDocumentName = distinguisherReplacer.replace(newDocumentName.length() - 2, newDocumentName.length() - 1, new Integer(matchingFilenameDistinguisher).toString()).toString(); newDocument.setDocumentName(newDocumentName); } } Scanner tokenizer = null; FileChannel fileSource = null; FileChannel collectionDestination = null; HashMap<String, Integer> termHashMap = new HashMap<String, Integer>(); Index collectionIndex = activeCollection.getIndex(); int documentTermMaxFrequency = 0; int currentTermFrequency; try { tokenizer = new Scanner(new BufferedReader(new FileReader(selectedFile))); tokenizer.useDelimiter(Pattern.compile("\\p{Space}|\\p{Punct}|\\p{Cntrl}")); String nextToken; while (tokenizer.hasNext()) { nextToken = tokenizer.next().toLowerCase(); if (!nextToken.isEmpty()) if (termHashMap.containsKey(nextToken)) termHashMap.put(nextToken, termHashMap.get(nextToken) + 1); else termHashMap.put(nextToken, 1); } Term newTerm; for (String term : termHashMap.keySet()) { newTerm = new Term(term); if (!collectionIndex.termExists(newTerm)) collectionIndex.addTerm(newTerm); currentTermFrequency = termHashMap.get(term); if (currentTermFrequency > documentTermMaxFrequency) documentTermMaxFrequency = currentTermFrequency; collectionIndex.addOccurence(newTerm, newDocument, currentTermFrequency); } activeCollection.addDocument(newDocument); String userHome = System.getProperty("user.home"); String fileSeparator = System.getProperty("file.separator"); collectionCopyFile = new File(userHome + fileSeparator + "Infrared" + fileSeparator + activeCollection.getDocumentCollectionName() + fileSeparator + newDocumentName); collectionCopyFile.createNewFile(); fileSource = new FileInputStream(selectedFile).getChannel(); collectionDestination = new FileOutputStream(collectionCopyFile).getChannel(); collectionDestination.transferFrom(fileSource, 0, fileSource.size()); } catch (FileNotFoundException e) { System.err.println(e.getMessage() + " This error should never occur! The file was just selected!"); return; } catch (IOException e) { JOptionPane.showMessageDialog(this, "An I/O error occured during file transfer!", "File transfer I/O error", JOptionPane.WARNING_MESSAGE); return; } finally { try { if (tokenizer != null) tokenizer.close(); if (fileSource != null) fileSource.close(); if (collectionDestination != null) collectionDestination.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (evt.getActionCommand().equalsIgnoreCase(JFileChooser.CANCEL_SELECTION)) processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } |
11
| Code Sample 1:
public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } }
Code Sample 2:
void copyFileAscii(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { System.err.println(ex.toString()); } } |
11
| Code Sample 1:
private void anneal(final float maxGamma, final float gammaAccel, final float objectiveTolerance, final float objectiveAccel, final float scoreTolerance, final float paramTolerance, final float distanceLimit, final float randomLimit, final long randomSeed, final BufferedDocuments<Phrase> references, final int n, final int maxNbest, File stateFile, boolean keepState) { float gamma = 0; boolean annealObjective = true; double[] convergedScores = new double[n]; double[] totalLogScores = new double[n]; boolean[] isConverged = new boolean[n]; GradientPoint[] initPoints = new GradientPoint[n]; GradientPoint[] prevInitPoints = new GradientPoint[n]; GradientPoint[] bestInitPoints = new GradientPoint[n]; GradientPoint[] prevMinPoints = new GradientPoint[n]; Random rand = new Random(randomSeed); Time time = new Time(); if (stateFile != null && stateFile.length() > 0) { time.reset(); try { ObjectInputStream stream = new ObjectInputStream(new FileInputStream(stateFile)); gamma = stream.readFloat(); annealObjective = stream.readBoolean(); convergedScores = (double[]) stream.readObject(); totalLogScores = (double[]) stream.readObject(); isConverged = (boolean[]) stream.readObject(); initPoints = (GradientPoint[]) stream.readObject(); prevInitPoints = (GradientPoint[]) stream.readObject(); bestInitPoints = (GradientPoint[]) stream.readObject(); prevMinPoints = (GradientPoint[]) stream.readObject(); rand = (Random) stream.readObject(); int size = stream.readInt(); for (int id = 0; id < size; id++) { Feature feature = FEATURES.getRaw(CONFIG, stream.readUTF(), 0f); if (feature.getId() != id) throw new Exception("Features have changed"); } evaluation.read(stream); stream.close(); output.println("# Resuming from previous optimization state (" + time + ")"); output.println(); } catch (Exception e) { e.printStackTrace(); Log.getInstance().severe("Failed loading optimization state (" + stateFile + "): " + e.getMessage()); } } else { final int evaluations = ProjectedEvaluation.CFG_OPT_HISTORY_SIZE.getValue(); final GradientPoint[] randPoints = new GradientPoint[n * evaluations]; for (int i = 0; i < n; i++) { evaluation.setParallelId(i); for (int j = 0; j < evaluations; j++) { if (i != 0) randPoints[i * n + j] = getRandomPoint(rand, randPoints[0], distanceLimit, null); evaluate(references, i + ":" + j); if (i == 0) { randPoints[0] = new GradientPoint(evaluation, null); gamma = LogFeatureModel.FEAT_MODEL_GAMMA.getValue(); break; } } } for (int i = 0; i < randPoints.length; i++) if (randPoints[i] != null) randPoints[i] = new GradientPoint(evaluation, randPoints[i], output); for (int i = 0; i < n; i++) { prevInitPoints[i] = null; initPoints[i] = randPoints[i * n]; if (i != 0) for (int j = 1; j < evaluations; j++) if (randPoints[i * n + j].getScore() < initPoints[i].getScore()) initPoints[i] = randPoints[i * n + j]; bestInitPoints[i] = initPoints[i]; convergedScores[i] = Float.MAX_VALUE; } } for (int searchCount = 1; ; searchCount++) { boolean isFinished = true; for (int i = 0; i < n; i++) isFinished = isFinished && isConverged[i]; if (isFinished) { output.println("*** N-best list converged. Modifying annealing schedule. ***"); output.println(); if (annealObjective) { boolean objectiveConverged = true; for (int i = 0; objectiveConverged && i < n; i++) objectiveConverged = isConverged(bestInitPoints[i].getScore(), convergedScores[i], objectiveTolerance, SCORE_EPSILON); annealObjective = false; for (Metric<ProjectedSentenceEvaluation> metric : AbstractEvaluation.CFG_EVAL_METRICS.getValue()) if (metric.doAnnealing()) { float weight = metric.getWeight(); if (weight != 0) if (objectiveConverged) metric.setWeight(0); else { annealObjective = true; metric.setWeight(weight / objectiveAccel); } } } if (!annealObjective) { if (Math.abs(gamma) >= maxGamma) { GradientPoint bestPoint = bestInitPoints[0]; for (int i = 1; i < n; i++) if (bestInitPoints[i].getScore() < bestPoint.getScore()) bestPoint = bestInitPoints[i]; output.format("Best Score: %+.7g%n", bestPoint.getScore()); output.println(); bestPoint = new GradientPoint(evaluation, bestPoint, output); break; } gamma *= gammaAccel; if (Math.abs(gamma) + GAMMA_EPSILON >= maxGamma) gamma = gamma >= 0 ? maxGamma : -maxGamma; } for (int i = 0; i < n; i++) { convergedScores[i] = bestInitPoints[i].getScore(); initPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], gamma, output); bestInitPoints[i] = initPoints[i]; prevInitPoints[i] = null; prevMinPoints[i] = null; isConverged[i] = false; } searchCount = 0; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; if (n > 1) output.println("Minimizing point " + i); Gradient gradient = initPoints[i].getGradient(); for (int id = 0; id < FEATURES.size(); id++) output.format("GRAD %-65s %-+13.7g%n", FEATURES.getName(id), gradient.get(id)); output.println(); time.reset(); GradientPoint minPoint = minimize(initPoints[i], prevInitPoints[i], bestInitPoints[i], scoreTolerance, paramTolerance, distanceLimit, randomLimit, rand); final float[] weights = minPoint.getWeights(); for (int j = 0; j < weights.length; j++) output.format("PARM %-65s %-+13.7g%n", FEATURES.getName(j), weights[j]); output.println(); output.format("Minimum Score: %+.7g (average distance of %.2f)%n", minPoint.getScore(), minPoint.getAverageDistance()); output.println(); output.println("# Minimized gradient (" + time + ")"); output.println(); output.flush(); isConverged[i] = weights == initPoints[i].getWeights(); prevInitPoints[i] = initPoints[i]; prevMinPoints[i] = minPoint; initPoints[i] = minPoint; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; isConverged[i] = isConvergedScore("minimum", prevMinPoints[i], prevInitPoints[i], scoreTolerance) && isConvergedWeights(prevMinPoints[i], prevInitPoints[i], paramTolerance); prevMinPoints[i].setWeightsAndRescore(evaluation); evaluation.setParallelId(i); evaluate(references, Integer.toString(i)); } Set<Point> prunePoints = new HashSet<Point>(); prunePoints.addAll(Arrays.asList(bestInitPoints)); prunePoints.addAll(Arrays.asList(prevInitPoints)); prunePoints.addAll(Arrays.asList(initPoints)); evaluation.prune(prunePoints, maxNbest, output); for (int i = 0; i < n; i++) { final boolean bestIsPrev = bestInitPoints[i] == prevInitPoints[i]; final boolean bestIsInit = bestInitPoints[i] == initPoints[i]; bestInitPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], bestIsInit ? output : null); if (bestIsPrev) prevInitPoints[i] = bestInitPoints[i]; if (bestIsInit) initPoints[i] = bestInitPoints[i]; if (!bestIsPrev && prevInitPoints[i] != null) { prevInitPoints[i] = new GradientPoint(evaluation, prevInitPoints[i], null); if (prevInitPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = prevInitPoints[i]; } if (!bestIsInit) { initPoints[i] = new GradientPoint(evaluation, initPoints[i], output); if (initPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = initPoints[i]; } } for (int i = 0; i < n; i++) if (isConverged[i]) if (prevMinPoints[i] == null) { output.println("# Convergence failed: no previous minimum is defined"); output.println(); isConverged[i] = false; } else { isConverged[i] = isConvergedScore("best known", bestInitPoints[i], initPoints[i], scoreTolerance) && isConvergedScore("previous minimum", prevMinPoints[i], initPoints[i], scoreTolerance); } if (stateFile != null) { time.reset(); try { File dir = stateFile.getCanonicalFile().getParentFile(); File temp = File.createTempFile("cunei-opt-", ".tmp", dir); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(temp)); stream.writeFloat(gamma); stream.writeBoolean(annealObjective); stream.writeObject(convergedScores); stream.writeObject(totalLogScores); stream.writeObject(isConverged); stream.writeObject(initPoints); stream.writeObject(prevInitPoints); stream.writeObject(bestInitPoints); stream.writeObject(prevMinPoints); stream.writeObject(rand); stream.writeInt(FEATURES.size()); for (int id = 0; id < FEATURES.size(); id++) stream.writeUTF(FEATURES.getName(id)); evaluation.write(stream); stream.close(); if (!temp.renameTo(stateFile)) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(temp).getChannel(); out = new FileOutputStream(stateFile).getChannel(); in.transferTo(0, in.size(), out); temp.delete(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } output.println("# Saved optimization state (" + time + ")"); output.println(); } catch (IOException e) { Log.getInstance().severe("Failed writing optimization state: " + e.getMessage()); } } } if (stateFile != null && !keepState) stateFile.delete(); }
Code Sample 2:
public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } |
00
| Code Sample 1:
public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
Code Sample 2:
private String createHash() { String hash = ""; try { final java.util.Calendar c = java.util.Calendar.getInstance(); String day = "" + c.get(java.util.Calendar.DATE); day = (day.length() == 1) ? '0' + day : day; String month = "" + (c.get(java.util.Calendar.MONTH) + 1); month = (month.length() == 1) ? '0' + month : month; final String hashString = getStringProperty("hashkey") + day + "." + month + "." + c.get(java.util.Calendar.YEAR); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(hashString.getBytes()); final byte digest[] = md.digest(); hash = ""; for (int i = 0; i < digest.length; i++) { final String s = Integer.toHexString(digest[i] & 0xFF); hash += ((s.length() == 1) ? "0" + s : s); } } catch (final NoSuchAlgorithmException e) { bot.getLogger().log(e); } return hash; } |
11
| Code Sample 1:
public String getRssFeedUrl(boolean searchWeb) { String rssFeedUrl = null; if (entity.getNewsFeedUrl() != null & !entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (entity.getUrl() == null || entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (searchWeb) { HttpURLConnection con = null; InputStream is = null; try { URL url = new URL(entity.getUrl()); con = (HttpURLConnection) url.openConnection(); con.connect(); is = con.getInputStream(); InputStreamReader sr = new InputStreamReader(is); BufferedReader br = new BufferedReader(sr); String ln; StringBuffer sb = new StringBuffer(); while ((ln = br.readLine()) != null) { sb.append(ln + "\n"); } rssFeedUrl = extractRssFeedUrl(sb.toString()); } catch (Exception e) { log.error(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(e); } } if (con != null) { con.disconnect(); } } } return rssFeedUrl; }
Code Sample 2:
public void prepareOutput(HttpServletRequest req) { EaasyStreet.logTrace(METHOD_IN + className + OUTPUT_METHOD); super.prepareOutput(req); String content = Constants.EMPTY_STRING; String rawContent = null; List parts = null; try { URL url = new URL(sourceUrl); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); buffer.append(Constants.LF); } rawContent = buffer.toString(); } catch (FileNotFoundException nf) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", nf.getMessage(), nf.toString() })); } catch (Exception e) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", e.getMessage(), e.toString() })); } if (rawContent != null) { if (startDelimiter != null) { parts = StringUtils.split(rawContent, startDelimiter); if (parts != null && parts.size() > 1) { rawContent = (String) parts.get(1); if (parts.size() > 2) { for (int x = 2; x < parts.size(); x++) { rawContent += startDelimiter; rawContent += parts.get(x); } } } else { rawContent = null; } } } if (rawContent != null) { if (endDelimiter != null) { parts = StringUtils.split(rawContent, endDelimiter); if (parts != null && parts.size() > 0) { rawContent = (String) parts.get(0); } else { rawContent = null; } } } if (rawContent != null) { if (replacementValues != null && !replacementValues.isEmpty()) { for (int x = 0; x < replacementValues.size(); x++) { LabelValueBean bean = (LabelValueBean) replacementValues.get(x); rawContent = StringUtils.replace(rawContent, bean.getLabel(), bean.getValue()); } } } if (rawContent != null) { content = rawContent; } req.setAttribute(getFormName(), content); EaasyStreet.logTrace(METHOD_OUT + className + OUTPUT_METHOD); } |
11
| Code Sample 1:
public static void copyFile(String original, String destination) throws Exception { File original_file = new File(original); File destination_file = new File(destination); if (!original_file.exists()) throw new Exception("File with path " + original + " does not exist."); if (destination_file.exists()) throw new Exception("File with path " + destination + " already exists."); FileReader in = new FileReader(original_file); FileWriter out = new FileWriter(destination_file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } } |
00
| Code Sample 1:
public static void copyFile(File sourceFile, File targetFile) throws FileCopyingException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileCopyingException(exceptionMessage, ioException); } }
Code Sample 2:
public static ByteBuffer readURL(URL url) throws IOException, MalformedURLException { URLConnection connection = null; try { connection = url.openConnection(); return readInputStream(new BufferedInputStream(connection.getInputStream())); } catch (IOException e) { throw e; } } |
11
| Code Sample 1:
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } }
Code Sample 2:
public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } } |
11
| Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
@Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; boolean checkPassword1 = false; boolean checkPassword2 = false; sql = "select password from Usuarios where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { Tree tree1 = CreateTree(password, 0); Tree tree2 = CreateTree(password, 1); tree1.enumerateTree(tree1.root); tree2.enumerateTree(tree2.root); for (int i = 0; i < tree1.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree1.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword1 = true; break; } else checkPassword1 = false; } for (int i = 0; i < tree2.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree2.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword2 = true; break; } else checkPassword2 = false; } if (checkPassword1 == true || checkPassword2 == true) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); setTries(0); setVisible(false); Error.log(3003, "Senha pessoal verificada positivamente."); Error.log(3002, "Autentica��o etapa 2 encerrada."); PasswordTableWindow ptw = new PasswordTableWindow(login); ptw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); Error.log(3004, "Senha pessoal verificada negativamente."); int tries = getTries(); if (tries == 0) { Error.log(3005, "Primeiro erro da senha pessoal contabilizado."); } else if (tries == 1) { Error.log(3006, "Segundo erro da senha pessoal contabilizado."); } else if (tries == 2) { Error.log(3007, "Terceiro erro da senha pessoal contabilizado."); Error.log(3008, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 2."); Error.log(3002, "Autentica��o etapa 2 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } if (e.getSource() == btnClear) { passwordField.setText(""); } } |
00
| Code Sample 1:
public void copyFile(final File sourceFile, final File destinationFile) throws FileIOException { final FileChannel sourceChannel; try { sourceChannel = new FileInputStream(sourceFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, sourceFile, exception); } final FileChannel destinationChannel; try { destinationChannel = new FileOutputStream(destinationFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, destinationFile, exception); } try { destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (Exception exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, null, exception); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException exception) { LOGGER.error("closing source", exception); } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException exception) { LOGGER.error("closing destination", exception); } } } }
Code Sample 2:
public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } |
00
| Code Sample 1:
public static void main(String[] args) throws IOException { PostParameter a1 = new PostParameter("v", Utils.encode("1.0")); PostParameter a2 = new PostParameter("api_key", Utils.encode(RenRenConstant.apiKey)); PostParameter a3 = new PostParameter("method", Utils.encode("notifications.send")); PostParameter a4 = new PostParameter("call_id", System.nanoTime()); PostParameter a5 = new PostParameter("session_key", Utils.encode("5.22af9ee9ad842c7eb52004ece6e96b10.86400.1298646000-350727914")); PostParameter a6 = new PostParameter("to_ids", Utils.encode("350727914")); PostParameter a7 = new PostParameter("notification", "又到了要睡觉的时间了。"); PostParameter a8 = new PostParameter("format", Utils.encode("JSON")); RenRenPostParameters ps = new RenRenPostParameters(Utils.encode(RenRenConstant.secret)); ps.addParameter(a1); ps.addParameter(a2); ps.addParameter(a3); ps.addParameter(a4); ps.addParameter(a5); ps.addParameter(a6); ps.addParameter(a7); ps.addParameter(a8); System.out.println(RenRenConstant.apiUrl + "?" + ps.generateUrl()); URL url = new URL(RenRenConstant.apiUrl + "?" + ps.generateUrl()); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput(true); request.setRequestMethod("POST"); System.out.println("Sending request..."); request.connect(); System.out.println("Response: " + request.getResponseCode() + " " + request.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String b = null; while ((b = reader.readLine()) != null) { System.out.println(b); } }
Code Sample 2:
public void download(String contentUuid, File path) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream output = new FileOutputStream(path); IoUtils.copyBytes(inputStream, output); IoUtils.close(inputStream); IoUtils.close(output); } catch (IOException ioex) { throw new WebServiceClientException("Could not download or saving content to path [" + path.getAbsolutePath() + "]", ioex); } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } } |
11
| Code Sample 1:
private void retrieveData() { StringBuffer obsBuf = new StringBuffer(); try { URL url = new URL(getProperty("sourceURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String lineIn = null; while ((lineIn = in.readLine()) != null) { if (GlobalProps.DEBUG) { logger.log(Level.FINE, "WebSource retrieveData: " + lineIn); } obsBuf.append(lineIn); } String fmt = getProperty("dataFormat"); if (GlobalProps.DEBUG) { logger.log(Level.FINE, "Raw: " + obsBuf.toString()); } if ("NWS XML".equals(fmt)) { obs = new NWSXmlObservation(obsBuf.toString()); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't connect to: " + getProperty("sourceURL")); if (GlobalProps.DEBUG) { e.printStackTrace(); } } }
Code Sample 2:
public List<BadassEntry> parse() { mBadassEntries = new ArrayList<BadassEntry>(); try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains(START_PARSE)) flag1 = true; if (flag1 && line.contains(STOP_PARSE)) break; if (flag1) { if (line.contains(ENTRY_HINT)) { parseBadass(line); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mBadassEntries; } |
11
| Code Sample 1:
public void delete(int id) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from Instructions where InstructionId = " + id; stmt.executeUpdate(sql); sql = "delete from InstructionGroups where InstructionId = " + id; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
Code Sample 2:
private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; } |
00
| Code Sample 1:
public RandomAccessFileOrArray(URL url) throws IOException { InputStream is = url.openStream(); try { this.arrayIn = InputStreamToArray(is); } finally { try { is.close(); } catch (IOException ioe) { } } }
Code Sample 2:
public byte[] encryptMsg(String encryptString) { byte[] encryptByte = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(encryptString.getBytes()); encryptByte = messageDigest.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return encryptByte; } |