label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
|
Code Sample 1:
@Override public void copy(final String fileName) throws FileIOException { final long savedCurrentPositionInFile = currentPositionInFile; if (opened) { closeImpl(); } final FileInputStream fis; try { fis = new FileInputStream(file); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + file, file, exception); } final File destinationFile = new File(fileName); final FileOutputStream fos; try { fos = new FileOutputStream(destinationFile); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + destinationFile, destinationFile, exception); } try { final byte[] buf = new byte[1024]; int readLength = 0; while ((readLength = fis.read(buf)) != -1) { fos.write(buf, 0, readLength); } } catch (IOException exception) { throw HELPER_FILE_UTIL.fileIOException("failed copy from " + file + " to " + destinationFile, null, exception); } finally { try { if (fis != null) { fis.close(); } } catch (Exception exception) { } try { if (fos != null) { fos.close(); } } catch (Exception exception) { } } if (opened) { openImpl(); seek(savedCurrentPositionInFile); } }
Code Sample 2:
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); 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[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
private void downloadFtp(File file, URL jurl) throws SocketException, IOException { System.out.println("downloadFtp(" + file + ", " + jurl + ")"); FTPClient client = new FTPClient(); client.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } }); try { client.connect(jurl.getHost(), -1 == jurl.getPort() ? FTP.DEFAULT_PORT : jurl.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); throw new IOException("FTP server refused connection."); } if (!client.login("anonymous", "anonymous")) { client.logout(); throw new IOException("Authentication failure."); } client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); FileOutputStream out = new FileOutputStream(file); boolean ok = client.retrieveFile(jurl.getPath(), out); out.close(); client.logout(); if (!ok) { throw new IOException("File transfer failure."); } } catch (IOException e) { throw e; } finally { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { } } } }
Code Sample 2:
public static final String encryptSHA(String decrypted) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(decrypted.getBytes()); byte hash[] = sha.digest(); sha.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; inputLine = in.readLine(); String dist_metric = in.readLine(); File outFile = new File("data.txt"); FileWriter outw = new FileWriter(outFile); outw.write(inputLine); outw.close(); File sample_coords = new File("sample_coords.txt"); sample_coords.delete(); File sp_coords = new File("sp_coords.txt"); sp_coords.delete(); try { System.out.println("Running python script..."); System.out.println("Command: " + "python l19test.py " + "\"" + dist_metric + "\""); Process pr = Runtime.getRuntime().exec("python l19test.py " + dist_metric); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Process Exit Value: " + exitVal); System.out.println("done."); } catch (Exception e) { System.out.println("Unable to run python script for PCoA analysis"); } File myFile = new File("sp_coords.txt"); byte[] mybytearray = new byte[(new Long(myFile.length())).intValue()]; FileInputStream fis = new FileInputStream(myFile); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); for (int i = 0; i < myFile.length(); i++) { out.writeByte(fis.read()); } myFile = new File("sample_coords.txt"); mybytearray = new byte[(int) myFile.length()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); myFile = new File("evals.txt"); mybytearray = new byte[(new Long(myFile.length())).intValue()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); out.flush(); out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
Code Sample 2:
private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; }
|
11
|
Code Sample 1:
public File copyFile(File f) throws IOException { File t = createNewFile("fm", "cpy"); FileOutputStream fos = new FileOutputStream(t); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return t; }
Code Sample 2:
private void copy(File from, File to) throws IOException { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); }
|
11
|
Code Sample 1:
public void overwriteFileTest() throws Exception { File filefrom = new File("/tmp/from.txt"); File fileto = new File("/tmp/to.txt"); InputStream from = null; OutputStream to = null; try { from = new FileInputStream(filefrom); to = new FileOutputStream(fileto); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } }
Code Sample 2:
protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
|
00
|
Code Sample 1:
private void loadProperties() throws IOException { if (properties == null) { return; } printDebugIfEnabled("Loading properties"); InputStream inputStream = configurationSource.openStream(); Properties newProperties = new Properties(); try { newProperties.load(inputStream); } finally { inputStream.close(); } String importList = newProperties.getProperty(KEY_IMPORT); if (importList != null) { importList = importList.trim(); if (importList.length() > 0) { String[] filesToImport = importList.split(","); if (filesToImport != null && filesToImport.length != 0) { String configurationContext = configurationSource.toExternalForm(); int lastSlash = configurationContext.lastIndexOf('/'); lastSlash += 1; configurationContext = configurationContext.substring(0, lastSlash); for (int i = 0; i < filesToImport.length; i++) { String filenameToImport = filesToImport[i]; URL urlToImport = new URL(configurationContext + filenameToImport); InputStream importStream = null; try { printDebugIfEnabled("Importing file", urlToImport); importStream = urlToImport.openStream(); newProperties.load(importStream); } catch (IOException e) { printError("Error importing properties file: " + filenameToImport + "(" + urlToImport + ")", e, true); } finally { if (importStream != null) importStream.close(); } } } } } if (devDebug) { Set properties = newProperties.entrySet(); printDebugIfEnabled("_____ Properties List START _____"); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); printDebugIfEnabled((String) entry.getKey(), entry.getValue()); } printDebugIfEnabled("______ Properties List END ______"); } properties.clear(); properties.putAll(newProperties); }
Code Sample 2:
public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
|
00
|
Code Sample 1:
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; }
Code Sample 2:
public synchronized int executeCommand(Vector<String> pvStatement) throws Exception { int ret = 0, i = 0; Statement stmt = null; String temp = ""; try { oConexion.setAutoCommit(false); stmt = oConexion.createStatement(); for (i = 0; i < pvStatement.size(); i++) { temp = (String) pvStatement.elementAt(i); ret += stmt.executeUpdate(temp); } oConexion.commit(); } catch (SQLException e) { oConexion.rollback(); throw e; } finally { stmt.close(); stmt = null; } return ret; }
|
00
|
Code Sample 1:
public static EXISchema getEXISchema(String fileName, Class<?> cls, EXISchemaFactoryErrorHandler compilerErrorHandler) throws IOException, ClassNotFoundException, EXISchemaFactoryException { EXISchemaFactory schemaCompiler = new EXISchemaFactory(); schemaCompiler.setCompilerErrorHandler(compilerErrorHandler); InputSource inputSource = null; if (fileName != null) { URL url; if ((url = cls.getResource(fileName)) != null) { inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); } else throw new RuntimeException("File '" + fileName + "' not found."); } EXISchema compiled = schemaCompiler.compile(inputSource); InputStream serialized = serializeSchema(compiled); return loadSchema(serialized); }
Code Sample 2:
public static void retriveRemote(ISource source, Node[] nodes, String outDirName, boolean isBinary) throws Exception { FTPClient client = new FTPClient(); client.connect(source.getSourceDetail().getHost()); client.login(source.getSourceDetail().getUser(), source.getSourceDetail().getPassword()); if (isBinary) client.setFileType(FTPClient.BINARY_FILE_TYPE); FileOutputStream out = null; for (Node node : nodes) { if (!node.isLeaf()) { Node[] childern = source.getChildern(node); File dir = new File(outDirName + File.separator + node.getAlias()); dir.mkdir(); retriveRemote(source, childern, outDirName + File.separator + node.getAlias(), isBinary); } else { out = new FileOutputStream(outDirName + File.separator + node.getAlias()); client.retrieveFile(node.getAbsolutePath(), out); out.flush(); out.close(); } } client.disconnect(); }
|
00
|
Code Sample 1:
public String putData(String id, String updatedNote, DefaultHttpClient httpclient) { try { HttpPut put = new HttpPut("http://3dforandroid.appspot.com/api/v1/note/update/" + id); StringEntity se = new StringEntity(updatedNote); se.setContentEncoding(HTTP.UTF_8); se.setContentType("application/json"); put.setEntity(se); put.setHeader("Content-Type", "application/json"); put.setHeader("Accept", "*/*"); HttpResponse response = httpclient.execute(put); HttpEntity entity = response.getEntity(); InputStream instream; instream = entity.getContent(); responseMessage = read(instream); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseMessage; }
Code Sample 2:
public ArrayList parseFile(File newfile) throws IOException { String s; String firstName; String header; String name = null; Integer PVLoggerID = new Integer(0); String[] tokens; int nvalues = 0; double num1, num2, num3; double xoffset = 1.0; double xdelta = 1.0; double yoffset = 1.0; double ydelta = 1.0; double zoffset = 1.0; double zdelta = 1.0; boolean readfit = false; boolean readraw = false; boolean zerodata = false; boolean baddata = false; boolean harpdata = false; ArrayList fitparams = new ArrayList(); ArrayList xraw = new ArrayList(); ArrayList yraw = new ArrayList(); ArrayList zraw = new ArrayList(); ArrayList sraw = new ArrayList(); ArrayList sxraw = new ArrayList(); ArrayList syraw = new ArrayList(); ArrayList szraw = new ArrayList(); URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; firstName = (String) tokens[0]; if (((String) tokens[0]).length() == 0) { readraw = false; readfit = false; continue; } if ((nvalues == 4) && (!firstName.startsWith("---"))) { if ((Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.)) { zerodata = true; } else { zerodata = false; } if (tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")) { baddata = true; } else { baddata = false; } } if (firstName.startsWith("start")) { header = s; } if (firstName.indexOf("WS") > 0) { if (name != null) { dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); } name = tokens[0]; readraw = false; readfit = false; zerodata = false; baddata = false; harpdata = false; fitparams.clear(); xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); } if (firstName.startsWith("Area")) ; if (firstName.startsWith("Ampl")) ; if (firstName.startsWith("Mean")) ; if (firstName.startsWith("Sigma")) { fitparams.add(new Double(Double.parseDouble(tokens[3]))); fitparams.add(new Double(Double.parseDouble(tokens[1]))); fitparams.add(new Double(Double.parseDouble(tokens[5]))); } if (firstName.startsWith("Offset")) ; if (firstName.startsWith("Slope")) ; if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Raw"))) { readraw = true; continue; } if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Fit"))) { readfit = true; continue; } if ((firstName.contains("Harp"))) { xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); harpdata = true; readraw = true; name = tokens[0]; continue; } if (firstName.startsWith("---")) continue; if (harpdata == true) { if (((String) tokens[0]).length() != 0) { if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } else { sxraw.add(new Double(Double.parseDouble(tokens[0]))); xraw.add(new Double(Double.parseDouble(tokens[1]))); syraw.add(new Double(Double.parseDouble(tokens[2]))); yraw.add(new Double(Double.parseDouble(tokens[3]))); szraw.add(new Double(Double.parseDouble(tokens[4]))); zraw.add(new Double(Double.parseDouble(tokens[5]))); } } continue; } if (readraw && (!zerodata) && (!baddata)) { sraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); sxraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); syraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); szraw.add(new Double(Double.parseDouble(tokens[0]))); yraw.add(new Double(Double.parseDouble(tokens[1]))); zraw.add(new Double(Double.parseDouble(tokens[2]))); xraw.add(new Double(Double.parseDouble(tokens[3]))); } if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } } dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); wiredata.add((Integer) PVLoggerID); return wiredata; }
|
00
|
Code Sample 1:
private void saveStateAsLast(URL url) { InputStream sourceStream = null; OutputStream destinationStream = null; File lastBundlesTxt = getLastBundleInfo(); try { try { destinationStream = new FileOutputStream(lastBundlesTxt); sourceStream = url.openStream(); SimpleConfiguratorUtils.transferStreams(sourceStream, destinationStream); } finally { if (destinationStream != null) destinationStream.close(); if (sourceStream != null) sourceStream.close(); } } catch (IOException e) { } }
Code Sample 2:
public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } }
|
00
|
Code Sample 1:
private static FacesBean.Type _createType() { try { ClassLoader cl = _getClassLoader(); URL url = cl.getResource("META-INF/faces-bean-type.properties"); if (url != null) { Properties properties = new Properties(); InputStream is = url.openStream(); try { properties.load(is); String className = (String) properties.get(UIXComponentBase.class.getName()); return (FacesBean.Type) cl.loadClass(className).newInstance(); } finally { is.close(); } } } catch (Exception e) { _LOG.severe("CANNOT_LOAD_TYPE_PROPERTIES", e); } return new FacesBean.Type(); }
Code Sample 2:
protected void checkWeavingJar() throws IOException { OutputStream out = null; try { final File weaving = new File(getWeavingPath()); if (!weaving.exists()) { new File(getWeavingFolder()).mkdir(); weaving.createNewFile(); final Path src = new Path("weaving/openfrwk-weaving.jar"); final InputStream in = FileLocator.openStream(getBundle(), src, false); out = new FileOutputStream(getWeavingPath(), true); IOUtils.copy(in, out); Logger.log(Logger.INFO, "Put weaving jar at location " + weaving); } else { Logger.getLog().info("File openfrwk-weaving.jar already exists at " + weaving); } } catch (final SecurityException e) { Logger.log(Logger.ERROR, "[SECURITY EXCEPTION] Not enough privilegies to create " + "folder and copy NexOpen weaving jar at location " + getWeavingFolder()); Logger.logException(e); } finally { if (out != null) { out.flush(); out.close(); } } }
|
00
|
Code Sample 1:
public static String getDeclaredXMLEncoding(URL url) throws IOException { InputStream stream = url.openStream(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(stream)); String firstLine = buffReader.readLine(); if (firstLine == null) { return SYSTEM_ENCODING; } int piStart = firstLine.indexOf("<?xml version=\"1.0\""); if (piStart != -1) { int attributeStart = firstLine.indexOf("encoding=\""); if (attributeStart >= 0) { int nextQuote = firstLine.indexOf('"', attributeStart + 10); if (nextQuote >= 0) { String encoding = firstLine.substring(attributeStart + 10, nextQuote); return encoding.trim(); } } } stream.close(); return SYSTEM_ENCODING; }
Code Sample 2:
private byte[] getFileFromFtp(String remote) throws Exception { ftp = new FTPClient(); int reply; ftp.connect(ftpServer); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("FTP server refused connection."); } if (!ftp.login(ftpUsername, ftpPassword)) { ftp.logout(); throw new Exception("Cann't login to ftp."); } ftp.enterLocalPassiveMode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ftp.retrieveFile(remote, baos); ftp.logout(); if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } return baos.toByteArray(); }
|
11
|
Code Sample 1:
public static void main(String arg[]) { try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } }
Code Sample 2:
public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); }
|
11
|
Code Sample 1:
public static void copyFile(final String src, final String dest) { Runnable r1 = new Runnable() { public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } } }; Thread cFile = new Thread(r1, "copyFile"); cFile.start(); }
Code Sample 2:
public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
|
00
|
Code Sample 1:
public static String encriptarContrasena(String contrasena) throws NoSuchAlgorithmException, UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(contrasena.getBytes("UTF-8")); byte[] digestBytes = md.digest(); String hex = null; for (int i = 0; i < digestBytes.length; i++) { hex = Integer.toHexString(0xFF & digestBytes[i]); if (hex.length() < 2) sb.append("0"); sb.append(hex); } return new String(sb); }
Code Sample 2:
private void addPNMLFileToLibrary(File selected) { try { FileChannel srcChannel = new FileInputStream(selected.getAbsolutePath()).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(matchingOrderXML).getParent() + "/" + selected.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); order.add(new ComponentDescription(false, selected.getName().replaceAll(".pnml", ""), 1.0)); updateComponentList(); } catch (IOException ioe) { JOptionPane.showMessageDialog(dialog, "Could not add the PNML file " + selected.getName() + " to the library!"); } }
|
00
|
Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } }
Code Sample 2:
public String getNextObjectId() throws SQLException { long nextserial = 1; String s0 = "lock table serials in exclusive mode"; String s1 = "SELECT nextserial FROM serials WHERE tablename = 'SERVER_OIDS'"; String s2; try { Statement stmt = dbconnect.connection.createStatement(); stmt.executeUpdate(s0); ResultSet rs = stmt.executeQuery(s1); if (!rs.next()) { s2 = "insert into serials (tablename,nextserial) values ('SERVER_OIDS', " + (nextserial) + ")"; } else { nextserial = rs.getLong(1) + 1; s2 = "update serials set nextserial=" + (nextserial) + " where tablename='SERVER_OIDS'"; } stmt.executeUpdate(s2); dbconnect.connection.commit(); rs.close(); stmt.close(); return "" + nextserial; } catch (SQLException e) { dbconnect.connection.rollback(); throw e; } }
|
11
|
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++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + 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 File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
|
00
|
Code Sample 1:
List HttpPost(URL url, List requestList) throws IOException { List responseList = new ArrayList(); URLConnection con; BufferedReader in; OutputStreamWriter out; StringBuffer req; String line; logInfo("HTTP POST: " + url); con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); out = new OutputStreamWriter(con.getOutputStream()); req = new StringBuffer(); for (int i = 0, n = requestList.size(); i < n; i++) { if (i != 0) req.append("&"); req.append(((HttpHeader) requestList.get(i)).key); req.append("="); if (((HttpHeader) requestList.get(i)).unicode) { StringBuffer tmp = new StringBuffer(200); byte[] uniBytes = ((HttpHeader) requestList.get(i)).value.getBytes("UnicodeBigUnmarked"); for (int j = 0; j < uniBytes.length; j++) tmp.append(Integer.toHexString(uniBytes[j]).length() == 1 ? "0" + Integer.toHexString(uniBytes[j]) : Integer.toHexString(uniBytes[j])); req.append(tmp.toString().replaceAll("ff", "")); } else req.append(((HttpHeader) requestList.get(i)).value); } out.write(req.toString()); out.flush(); out.close(); in = new BufferedReader(new InputStreamReader((con.getInputStream()))); while ((line = in.readLine()) != null) responseList.add(line); in.close(); return responseList; }
Code Sample 2:
public String hasheMotDePasse(String mdp) { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { } sha.reset(); sha.update(mdp.getBytes()); byte[] digest = sha.digest(); String pass = new String(Base64.encode(digest)); pass = "{SHA}" + pass; return pass; }
|
11
|
Code Sample 1:
public String fetch(final String address) throws EncoderException { final String escapedAddress = new URLCodec().encode(address); final String requestUrl = GeoCodeFetch.urlXmlPath + "&" + "address=" + escapedAddress; this.log.debug("requestUrl: {}", requestUrl); try { final StringBuffer sb = new StringBuffer(); final URL url = new URL(requestUrl); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { this.log.debug("line: {}", line); sb.append(line); } reader.close(); return (sb.toString()); } catch (final MalformedURLException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } catch (final IOException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } return (""); }
Code Sample 2:
protected void setOuterIP() { try { URL url = new URL("http://elm-ve.sf.net/ipCheck/ipCheck.cgi"); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ip = br.readLine(); ip = ip.trim(); bridgeOutIPTF.setText(ip); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private static void copy(File in, File out) throws IOException { if (!out.getParentFile().isDirectory()) out.getParentFile().mkdirs(); 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 importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } 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.toString()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
@Override public JSONObject runCommand(JSONObject payload, HttpSession session) throws DefinedException { String sessionId = session.getId(); log.debug("Login -> runCommand SID: " + sessionId); JSONObject toReturn = new JSONObject(); boolean isOK = true; String username = null; try { username = payload.getString(ComConstants.LogIn.Request.USERNAME); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing username parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } String password = null; if (isOK) { try { password = payload.getString(ComConstants.LogIn.Request.PASSWORD); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing password parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } } if (isOK) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("SessionId=" + sessionId + ", MD5 algorithm does not exist", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } m.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, m.digest()).toString(16); UserSession userSession = pli.login(username, password); try { if (userSession != null) { session.setAttribute("user", userSession); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_OK.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_OK.getStatusMessage()); } else { log.error("SessionId=" + sessionId + ", Login failed: username=" + username + " not found"); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusMessage()); } } catch (JSONException e) { log.error("SessionId=" + sessionId + ", JSON exception occured in response", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } } log.debug("Login <- runCommand SID: " + sessionId); return toReturn; }
Code Sample 2:
private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } }
|
11
|
Code Sample 1:
public static void copyFile(String target, String source) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { ExceptionHelper.showErrorDialog(e); } }
Code Sample 2:
public static final boolean compressToZip(final String sSource, final String sDest, final boolean bDeleteSourceOnSuccess) { ZipOutputStream os = null; InputStream is = null; try { os = new ZipOutputStream(new FileOutputStream(sDest)); is = new FileInputStream(sSource); final byte[] buff = new byte[1024]; int r; String sFileName = sSource; if (sFileName.indexOf('/') >= 0) sFileName = sFileName.substring(sFileName.lastIndexOf('/') + 1); os.putNextEntry(new ZipEntry(sFileName)); while ((r = is.read(buff)) > 0) os.write(buff, 0, r); is.close(); os.flush(); os.closeEntry(); os.close(); } catch (Throwable e) { Log.log(Log.WARNING, "lazyj.Utils", "compressToZip : cannot compress '" + sSource + "' to '" + sDest + "' because", e); return false; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } if (os != null) { try { os.close(); } catch (IOException ioe) { } } } if (bDeleteSourceOnSuccess) try { if (!(new File(sSource)).delete()) Log.log(Log.WARNING, "lazyj.Utils", "compressToZip: could not delete original file (" + sSource + ")"); } catch (SecurityException se) { Log.log(Log.ERROR, "lazyj.Utils", "compressToZip: security constraints prevents file deletion"); } return true; }
|
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:
public static void copyFile(String inName, String otName) throws Exception { File inFile = null; File otFile = null; try { inFile = new File(inName); otFile = new File(otName); } catch (Exception e) { e.printStackTrace(); } if (inFile == null || otFile == null) return; FileChannel sourceChannel = new FileInputStream(inFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(otFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
public static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
public static String encryptPasswd(String pass) { try { if (pass == null || pass.length() == 0) return pass; MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(pass.getBytes("UTF-8")); return Base64OutputStream.encode(sha.digest()); } catch (Throwable t) { throw new SystemException(t); } }
|
11
|
Code Sample 1:
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); }
|
00
|
Code Sample 1:
public void fetchKey() throws IOException { String strurl = MessageFormat.format(keyurl, new Object[] { username, secret, login, session }); StringBuffer result = new StringBuffer(); BufferedReader reader = null; URL url = null; try { url = new URL(strurl); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { result.append(line); } } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } Pattern p = Pattern.compile("<key>(.*)</key>"); Matcher m = p.matcher(result.toString()); if (m.matches()) { this.key = m.group(1); } }
Code Sample 2:
private void copyFile(File source, File destination) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(destination); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int readCount = 0; while ((readCount = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, readCount); } } finally { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
|
00
|
Code Sample 1:
private String computeHash(String str) { StringBuffer hexBuffer = new StringBuffer(); byte[] bytes; int i; try { MessageDigest hashAlgorithm = MessageDigest.getInstance(hashAlgorithmName); hashAlgorithm.reset(); hashAlgorithm.update(str.getBytes()); bytes = hashAlgorithm.digest(); } catch (NoSuchAlgorithmException e) { return null; } for (i = 0; i < bytes.length; i++) hexBuffer.append(((bytes[i] >= 0 && bytes[i] <= 15) ? "0" : "") + Integer.toHexString(bytes[i] & 0xFF)); return hexBuffer.toString(); }
Code Sample 2:
public void testLocalUserAccountLocalRemoteRoles() throws SQLException { Statement st = null; Connection authedCon = null; try { saSt.executeUpdate("CREATE USER tlualrr PASSWORD 'wontuse'"); saSt.executeUpdate("GRANT role3 TO tlualrr"); saSt.executeUpdate("GRANT role4 TO tlualrr"); saSt.executeUpdate("SET DATABASE AUTHENTICATION FUNCTION EXTERNAL NAME " + "'CLASSPATH:" + getClass().getName() + ".twoRolesFn'"); try { authedCon = DriverManager.getConnection(jdbcUrl, "TLUALRR", "unusedPassword"); } catch (SQLException se) { fail("Access with 'twoRolesFn' failed"); } st = authedCon.createStatement(); assertFalse("Positive test #1 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t1 VALUES(1)")); assertFalse("Positive test #2 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t2 VALUES(2)")); assertTrue("Negative test #3 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t3 VALUES(3)")); assertTrue("Negative test #4 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t4 VALUES(4)")); assertEquals(twoRolesSet, AuthUtils.getEnabledRoles(authedCon)); } finally { if (st != null) try { st.close(); } catch (SQLException se) { logger.error("Close of Statement failed:" + se); } finally { st = null; } if (authedCon != null) try { authedCon.rollback(); authedCon.close(); } catch (SQLException se) { logger.error("Close of Authed Conn. failed:" + se); } finally { authedCon = null; } } }
|
11
|
Code Sample 1:
public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); 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; } }
Code Sample 2:
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(); } }
|
00
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { FileChannel from = new FileInputStream(src).getChannel(); FileChannel to = new FileOutputStream(dst).getChannel(); from.transferTo(0, src.length(), to); from.close(); to.close(); }
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(); }
|
00
|
Code Sample 1:
public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } }
Code Sample 2:
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
|
00
|
Code Sample 1:
private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
Code Sample 2:
public String execute(Map params, String body, RenderContext renderContext) throws MacroException { loadData(); String from = (String) params.get("from"); if (body.length() > 0 && from != null) { try { URL url; String serverUser = null; String serverPassword = null; url = new URL(semformsSettings.getZRapServerUrl() + "ZRAP_QueryProcessor.php?from=" + URLEncoder.encode(from, "utf-8") + "&query=" + URLEncoder.encode(body, "utf-8")); if (url.getUserInfo() != null) { String[] userInfo = url.getUserInfo().split(":"); if (userInfo.length == 2) { serverUser = userInfo[0]; serverPassword = userInfo[1]; } } URLConnection connection = null; InputStreamReader bf; if (serverUser != null && serverPassword != null) { connection = url.openConnection(); String encoding = new sun.misc.BASE64Encoder().encode((serverUser + ":" + serverPassword).getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); bf = new InputStreamReader(connection.getInputStream()); } else { bf = new InputStreamReader(url.openStream()); } BufferedReader bbf = new BufferedReader(bf); String line = bbf.readLine(); String buffer = ""; while (line != null) { buffer += line; line = bbf.readLine(); } return buffer; } catch (Exception e) { e.printStackTrace(); return "ERROR:" + e.getLocalizedMessage(); } } else return "Please write an RDQL query in the macro as body and an url of the model as 'from' parameter"; }
|
00
|
Code Sample 1:
private long getLastModification() { try { if (connection == null) connection = url.openConnection(); return connection.getLastModified(); } catch (IOException e) { LOG.warn("URL could not be opened: " + e.getMessage(), e); return 0; } }
Code Sample 2:
public boolean loadURL(URL url) { try { propertyBundle.load(url.openStream()); LOG.info("Configuration loaded from " + url + "\n"); return true; } catch (Exception e) { if (canComplain) { LOG.warn("Unable to load configuration " + url + "\n"); } canComplain = false; return false; } }
|
00
|
Code Sample 1:
public void listgroups() throws Exception { String lapage = new String(""); Pattern pat; Matcher mat; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearAll(); System.out.print("http://groups.yahoo.com/mygroups : "); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("."); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<td class=\"grpname selected\"><a href=\"(.+?)\".*?><em>(.+?)</em></a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(mat.group(2), "", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<a href=\"(.+?)\">Next ></a>"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); System.out.println(""); }
Code Sample 2:
@Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { File result = new File(parent, doc.getName()); if (doc instanceof XMLDOMDocument) { new PlainXMLDocumentWriter(result).writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { IOUtils.copy(bin.getContent().getInputStream(), new FileOutputStream(result)); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
|
11
|
Code Sample 1:
private void copy(final File src, final File dstDir) { dstDir.mkdirs(); final File dst = new File(dstDir, src.getName()); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(src), "ISO-8859-1")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "ISO-8859-1")); String read; while ((read = reader.readLine()) != null) { Line line = new Line(read); if (line.isComment()) continue; writer.write(read); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (writer != null) { try { writer.flush(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void doImport(File f, boolean checkHosp) throws Exception { connector.getConnection().setAutoCommit(false); File base = f.getParentFile(); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String outFileName = entry.getName(); File outFile = new File(base, outFileName); OutputStream out = new FileOutputStream(outFile, false); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); } in.close(); importDirectory(base, checkHosp); connector.getConnection().commit(); }
|
00
|
Code Sample 1:
public void reload() throws SAXException, IOException { if (url != null) { java.io.InputStream is = url.openStream(); configDoc = builder.parse(is); is.close(); System.out.println("XML config file read correctly from " + url); } else { configDoc = builder.parse(configFile); System.out.println("XML config file read correctly from " + configFile); } }
Code Sample 2:
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!"); }
|
11
|
Code Sample 1:
public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm�nye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut�s sor�n hiba t�rt�nt!"); } } }
Code Sample 2:
public static boolean copyFile(File source, File dest) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } return true; }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public void parseFile(String filespec, URL documentBase) { DataInputStream in = null; if (filespec == null || filespec.length() == 0) { in = new DataInputStream(System.in); } else { try { URL url = null; if (documentBase == null && _documentBase != null) { documentBase = _documentBase; } if (documentBase == null) { url = new URL(filespec); } else { try { url = new URL(documentBase, filespec); } catch (NullPointerException e) { url = new URL(filespec); } } in = new DataInputStream(url.openStream()); } catch (MalformedURLException e) { try { in = new DataInputStream(new FileInputStream(filespec)); } catch (FileNotFoundException me) { _errorMsg = new String[2]; _errorMsg[0] = "File not found: " + filespec; _errorMsg[1] = me.getMessage(); return; } catch (SecurityException me) { _errorMsg = new String[2]; _errorMsg[0] = "Security Exception: " + filespec; _errorMsg[1] = me.getMessage(); return; } } catch (IOException ioe) { _errorMsg = new String[3]; _errorMsg[0] = "Failure opening URL: "; _errorMsg[1] = " " + filespec; _errorMsg[2] = ioe.getMessage(); return; } } try { BufferedReader din = new BufferedReader(new InputStreamReader(in)); String line = din.readLine(); while (line != null) { _parseLine(line); line = din.readLine(); } } catch (MalformedURLException e) { _errorMsg = new String[2]; _errorMsg[0] = "Malformed URL: " + filespec; _errorMsg[1] = e.getMessage(); return; } catch (IOException e) { _errorMsg = new String[2]; _errorMsg[0] = "Failure reading data: " + filespec; _errorMsg[1] = e.getMessage(); _errorMsg[1] = e.getMessage(); } finally { try { in.close(); } catch (IOException me) { } } }
|
00
|
Code Sample 1:
protected void innerProcess(CrawlURI curi) throws InterruptedException { if (!curi.isHttpTransaction()) { return; } if (!TextUtils.matches("^text.*$", curi.getContentType())) { return; } long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue(); try { maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue(); } catch (AttributeNotFoundException e) { logger.severe("Missing max-size-bytes attribute when processing " + curi.toString()); } if (maxsize < curi.getContentSize() && maxsize > -1) { return; } String regexpr = ""; try { regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR); } catch (AttributeNotFoundException e2) { logger.severe("Missing strip-reg-exp when processing " + curi.toString()); return; } ReplayCharSequence cs = null; try { cs = curi.getHttpRecorder().getReplayCharSequence(); } catch (Exception e) { curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage()); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr.length() == 0) { s = cs.toString(); } else { Matcher m = TextUtils.getMatcher(regexpr, cs); s = m.replaceAll(" "); TextUtils.recycleMatcher(m); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); if (logger.isLoggable(Level.FINEST)) { logger.finest("Recalculated content digest for " + curi.toString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue)); } curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
Code Sample 2:
public void testGetContentInputStream() { URL url; try { url = new URL("http://www.wurzer.org/" + "Homepage/Publikationen/Eintrage/2009/10/7_Wissen_dynamisch_organisieren_files/" + "KnowTech%202009%20-%20Wissen%20dynamisch%20organisieren.pdf"); InputStream in = url.openStream(); Content c = provider.getContent(in); assertNotNull(c); assertTrue(!c.getFulltext().isEmpty()); assertTrue(c.getModificationDate() < System.currentTimeMillis()); assertTrue(c.getAttributes().size() > 0); assertEquals("KnowTech 2009 - Wissen dynamisch organisieren", c.getAttributeByName("Title").getValue()); assertEquals("Joerg Wurzer", c.getAttributeByName("Author").getValue()); assertEquals("Pages", c.getAttributeByName("Creator").getValue()); assertNull(c.getAttributeByName("Keywords")); assertTrue(c.getFulltext().startsWith("Wissen dynamisch organisieren")); assertTrue(c.getAttributeByName("Author").isKey()); assertTrue(!c.getAttributeByName("Producer").isKey()); } catch (MalformedURLException e) { fail("Malformed url - " + e.getMessage()); } catch (IOException e) { fail("Couldn't read file - " + e.getMessage()); } }
|
00
|
Code Sample 1:
public RobotList<Location> sort_incr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value > enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; }
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; } }
|
11
|
Code Sample 1:
private String copy(PluginVersionDetail usePluginVersion, File runtimeRepository) { try { File tmpFile = null; try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); tmpFile.deleteOnExit(); URL url = new URL(usePluginVersion.getUri()); String destFilename = new File(url.getFile()).getName(); File destFile = new File(runtimeRepository, destFilename); InputStream in = null; FileOutputStream out = null; int bytesDownload = 0; long startTime = 0; long endTime = 0; try { URLConnection urlConnection = url.openConnection(); bytesDownload = urlConnection.getContentLength(); in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); startTime = System.currentTimeMillis(); IOUtils.copy(in, out); endTime = System.currentTimeMillis(); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } String downloadSpeedInfo = null; long downloadSpeed = 0; if ((endTime - startTime) > 0) { downloadSpeed = 1000L * bytesDownload / (endTime - startTime); } if (downloadSpeed == 0) { downloadSpeedInfo = "? B/s"; } else if (downloadSpeed < 1000) { downloadSpeedInfo = downloadSpeed + " B/s"; } else if (downloadSpeed < 1000000) { downloadSpeedInfo = downloadSpeed / 1000 + " KB/s"; } else if (downloadSpeed < 1000000000) { downloadSpeedInfo = downloadSpeed / 1000000 + " MB/s"; } else { downloadSpeedInfo = downloadSpeed / 1000000000 + " GB/s"; } String tmpFileMessageDigest = getMessageDigest(tmpFile.toURI().toURL()).getValue(); if (!tmpFileMessageDigest.equals(usePluginVersion.getMessageDigest().getValue())) { throw new RuntimeException("Downloaded file: " + usePluginVersion.getUri() + " does not have required message digest: " + usePluginVersion.getMessageDigest().getValue()); } if (!isNoop()) { FileUtils.copyFile(tmpFile, destFile); } return bytesDownload + " Bytes " + downloadSpeedInfo; } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download " + usePluginVersion.getUri() + " to " + runtimeRepository, ex); } }
Code Sample 2:
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } }
|
00
|
Code Sample 1:
public static void get_PK_data() { try { FileWriter file_writer = new FileWriter("xml_data/PK_data_dump.xml"); BufferedWriter file_buffered_writer = new BufferedWriter(file_writer); URL fdt = new URL("http://opendata.5t.torino.it/get_pk"); URLConnection url_connection = fdt.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(url_connection.getInputStream())); String input_line; int num_lines = 0; while ((input_line = in.readLine()) != null) { file_buffered_writer.write(input_line + "\n"); num_lines++; } System.out.println("Parking :: Writed " + num_lines + " lines."); in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
Code Sample 2:
private Date fetchLastModifiedDate(String archName) { Date modifdate = null; URL url = null; try { url = new URL(jEdit.getProperty(OOO_DICTS_PROP) + archName + ".zip"); } catch (MalformedURLException mfue) { Log.log(Log.ERROR, HunspellDictsManager.class, "Invalid archive name : " + archName); GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { mfue.getMessage() }); } if (url != null) { try { URLConnection connect = url.openConnection(); connect.connect(); if (connect.getLastModified() == 0) { Log.log(Log.ERROR, HunspellDictsManager.class, "no lastModifiedDate for " + archName); } else { modifdate = new Date(connect.getLastModified()); System.out.println("Modif date :" + DateFormat.getInstance().format(modifdate)); return modifdate; } } catch (IOException ioe) { GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { ioe.getMessage() }); ioe.printStackTrace(); } } return modifdate; }
|
11
|
Code Sample 1:
public void notifyIterationEnds(final IterationEndsEvent event) { log.info("moving files..."); File source = new File("deqsim.log"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log to its iteration directory."); } } int parallelCnt = 0; source = new File("deqsim.log." + parallelCnt); while (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log." + parallelCnt)); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log." + parallelCnt + " to its iteration directory."); } parallelCnt++; source = new File("deqsim.log." + parallelCnt); } source = new File("loads_out.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("loads_out.txt")); try { IOUtils.copyFile(source, destination); } catch (FileNotFoundException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } catch (IOException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } destination = new File("loads_in.txt"); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move loads_out.txt to loads_in.txt."); } } source = new File("linkprocs.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("linkprocs.txt")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move linkprocs.txt to its iteration directory."); } } }
Code Sample 2:
public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
private String getPage(String urlString) throws Exception { if (pageBuffer.containsKey(urlString)) return pageBuffer.get(urlString); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = null; StringBuilder page = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException ioe) { logger.warn("Failed to read web page"); } finally { if (in != null) { in.close(); } } return page.toString(); }
Code Sample 2:
public static String encrypt(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes("UTF-8")); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
Code Sample 2:
public static double[][] getCurrency() throws IOException { URL url = new URL("http://hk.finance.yahoo.com/currency"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "big5")); double currency[][] = new double[11][11]; while (true) { String line = in.readLine(); String reg = "<td\\s((align=\"right\"\\sclass=\"yfnc_tabledata1\")" + "|(class=\"yfnc_tabledata1\"\\salign=\"right\"))>" + "([\\d|\\.]+)</td>"; Matcher m = Pattern.compile(reg).matcher(line); int i = 0, j = 0; boolean isfound = false; while (m.find()) { isfound = true; currency[i][j] = Double.parseDouble(m.group(4)); if (j == 10) { j = 0; i++; } else j++; } if (isfound) break; } return currency; }
|
11
|
Code Sample 1:
public static void main(String[] argv) throws IOException { int i; for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; ++i; switch(argv[i - 1].charAt(1)) { case 'b': try { flag_predict_probability = (atoi(argv[i]) != 0); } catch (NumberFormatException e) { exit_with_help(); } break; default: System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1)); exit_with_help(); break; } } if (i >= argv.length || argv.length <= i + 2) { exit_with_help(); } BufferedReader reader = null; Writer writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET)); Model model = Linear.loadModel(new File(argv[i + 1])); doPredict(reader, writer, model); } finally { closeQuietly(reader); closeQuietly(writer); } }
Code Sample 2:
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(); }
|
11
|
Code Sample 1:
public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
private void copyJdbcDriverToWL(final WLPropertyPage page) { final File url = new File(page.getDomainDirectory()); final File lib = new File(url, "lib"); final File mysqlLibrary = new File(lib, NexOpenUIActivator.getDefault().getMySQLDriver()); if (!mysqlLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + NexOpenUIActivator.getDefault().getMySQLDriver())); fos = new FileOutputStream(mysqlLibrary); IOUtils.copy(driver, fos); } catch (final IOException e) { Logger.log(Logger.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); final Status status = new Status(Status.ERROR, NexOpenUIActivator.PLUGIN_ID, Status.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); ErrorDialog.openError(page.getShell(), "Bea WebLogic MSQL support", "Could not copy the MySQL Driver jar file to Bea WL", status); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException 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 static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
|
11
|
Code Sample 1:
public static void createModelZip(String filename, String tempdir) throws EDITSException { try { 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(); } catch (Exception e) { throw new EDITSException("Can not create a model in file " + filename + " from folder " + tempdir); } }
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:
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void sort(int[] mas) { int temp; boolean t = true; while (t) { t = false; for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { temp = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = temp; t = true; } } } }
Code Sample 2:
public BasicTraceImpl() { out = System.out; traceEnable = new HashMap(); URL url = Hive.getURL("trace.cfg"); if (url != null) try { InputStream input = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String line; for (line = line = in.readLine(); line != null; line = in.readLine()) { int i = line.indexOf("="); if (i > 0) { String name = line.substring(0, i).trim(); String value = line.substring(i + 1).trim(); traceEnable.put(name, Boolean.valueOf(value).booleanValue() ? ((Object) (Boolean.TRUE)) : ((Object) (Boolean.FALSE))); } } input.close(); } catch (IOException io) { System.out.println(io); } TRACE = getEnable(THIS); }
|
11
|
Code Sample 1:
public static void replaceAll(File file, String substitute, String substituteReplacement) throws IOException { log.debug("Replace " + substitute + " by " + substituteReplacement); Pattern pattern = Pattern.compile(substitute); FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); Charset charset = Charset.forName("ISO-8859-15"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cb = decoder.decode(bb); Matcher matcher = pattern.matcher(cb); String outString = matcher.replaceAll(substituteReplacement); log.debug(outString); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); PrintStream ps = new PrintStream(fos); ps.print(outString); ps.close(); fos.close(); }
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 decompressFile(File f) throws IOException { File target = new File(f.toString().substring(0, f.toString().length() - 3)); System.out.print("Decompressing: " + f.getName() + ".. "); long initialSize = f.length(); GZIPInputStream in = new GZIPInputStream(new FileInputStream(f)); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int read; while ((read = in.read(buf)) != -1) { fos.write(buf, 0, read); } System.out.println("Done."); fos.close(); in.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Decompressed size: " + endSize); }
Code Sample 2:
@Test public void testWriteAndReadBigger() 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); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
|
11
|
Code Sample 1:
protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = new ArrayList<Datastream>(); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); tDatastreams.add(tDatastream); tDatastreams.addAll(_zipFile.getFiles(tZipTempFileName)); return tDatastreams; }
Code Sample 2:
public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
|
00
|
Code Sample 1:
public void login(String UID, String PWD, int CTY) throws Exception { sSideURL = sSideURLCollection[CTY]; sUID = UID; sPWD = PWD; iCTY = CTY; sLoginLabel = getLoginLabel(sSideURL); String sParams = getLoginParams(); CookieHandler.setDefault(new ListCookieHandler()); URL url = new URL(sSideURL + sLoginURL); URLConnection conn = url.openConnection(); setRequestProperties(conn); conn.setDoInput(true); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(sParams); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = rd.readLine(); while (line != null) { sb.append(line + "\n"); line = rd.readLine(); } wr.close(); rd.close(); String sPage = sb.toString(); Pattern p = Pattern.compile(">Dein Penner<"); Matcher matcher = p.matcher(sPage); LogedIn = matcher.find(); }
Code Sample 2:
public synchronized String encrypt(String plaintext) { if (plaintext == null || plaintext.equals("")) { return plaintext; } String hash = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); hash = Base64.encodeBase64String(raw).replaceAll("\r\n", ""); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage()); } return hash; }
|
11
|
Code Sample 1:
public static String[] putFECSplitFile(String uri, File file, int htl, boolean mode) { FcpFECUtils fecutils = null; Vector segmentHeaders = null; Vector segmentFileMaps = new Vector(); Vector checkFileMaps = new Vector(); Vector segmentKeyMaps = new Vector(); Vector checkKeyMaps = new Vector(); int fileLength = (int) file.length(); String output = new String(); int maxThreads = frame1.frostSettings.getIntValue("splitfileUploadThreads"); Thread[] chunkThreads = null; String[][] chunkResults = null; Thread[] checkThreads = null; String[][] checkResults = null; int threadCount = 0; String board = getBoard(file); { fecutils = new FcpFECUtils(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getIntValue("nodePort")); synchronized (fecutils.getClass()) { try { segmentHeaders = fecutils.FECSegmentFile("OnionFEC_a_1_2", fileLength); } catch (Exception e) { } } int chunkCnt = 0; int checkCnt = 0; synchronized (fecutils.getClass()) { try { Socket fcpSock; BufferedInputStream fcpIn; PrintStream fcpOut; for (int i = 0; i < segmentHeaders.size(); i++) { int blockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount; int blockNo = 0; fcpSock = new Socket(InetAddress.getByName(frame1.frostSettings.getValue("nodeAddress")), frame1.frostSettings.getIntValue("nodePort")); fcpSock.setSoTimeout(1800000); fcpOut = new PrintStream(fcpSock.getOutputStream()); fcpIn = new BufferedInputStream(fcpSock.getInputStream()); FileInputStream fileIn = new FileInputStream(file); File[] chunkFiles = new File[blockCount]; { System.out.println("Processing segment " + i); fileIn.skip(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset); long segLength = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount * ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize; System.out.println("segLength = " + Long.toHexString(segLength)); String headerString = "SegmentHeader\n" + ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).reconstruct() + "EndMessage\n"; String dataHeaderString = "\0\0\0\2FECEncodeSegment\nMetadataLength=" + Long.toHexString(headerString.length()) + "\nDataLength=" + Long.toHexString(headerString.length() + segLength) + "\nData\n" + headerString; System.out.print(dataHeaderString); fcpOut.print(dataHeaderString); long count = 0; while (count < segLength) { byte[] buffer = new byte[(int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize]; System.out.println(Long.toHexString(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset + count)); int inbytes = fileIn.read(buffer); if (inbytes < 0) { System.out.println("End of input file - no data"); for (int j = 0; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes < buffer.length) { System.out.println("End of input file - not enough data"); for (int j = inbytes; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes > segLength - count) inbytes = (int) (segLength - count); fcpOut.write(buffer); File uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-" + chunkCnt + ".tmp"); chunkFiles[blockNo] = uploadMe; uploadMe.deleteOnExit(); FileOutputStream fileOut = new FileOutputStream(uploadMe); fileOut.write(buffer, 0, (int) inbytes); fileOut.close(); count += inbytes; chunkCnt++; ; blockNo++; if (blockNo >= blockCount) break; } segmentFileMaps.add(chunkFiles); fcpOut.flush(); fileIn.close(); } int checkNo = 0; int checkBlockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockCount; File[] checkFiles = new File[checkBlockCount]; File uploadMe = null; FileOutputStream outFile = null; { String currentLine; long checkBlockSize = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockSize; int checkPtr = 0; int length = 0; do { boolean started = false; currentLine = fecutils.getLine(fcpIn).trim(); if (currentLine.equals("DataChunk")) { started = true; } if (currentLine.startsWith("Length=")) { length = Integer.parseInt((currentLine.split("="))[1], 16); } if (currentLine.equals("Data")) { int currentRead; byte[] buffer = new byte[(int) length]; if (uploadMe == null) { uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-chk-" + checkCnt + ".tmp"); uploadMe.deleteOnExit(); outFile = new FileOutputStream(uploadMe); } currentRead = fcpIn.read(buffer); while (currentRead < length) { currentRead += fcpIn.read(buffer, currentRead, length - currentRead); } outFile.write(buffer); checkPtr += currentRead; if (checkPtr == checkBlockSize) { outFile.close(); checkFiles[checkNo] = uploadMe; uploadMe = null; checkNo++; checkCnt++; checkPtr = 0; } } } while (currentLine.length() > 0); checkFileMaps.add(checkFiles); } fcpOut.close(); fcpIn.close(); fcpSock.close(); } } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } int chunkNo = 0; int uploadedBytes = 0; for (int i = 0; i < segmentFileMaps.size(); i++) { File[] currentFileMap = (File[]) segmentFileMaps.get(i); chunkThreads = new Thread[currentFileMap.length]; chunkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Chunk: " + chunkNo); while (getActiveThreads(chunkThreads) >= maxThreads) mixed.wait(5000); chunkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, chunkResults, threadCount, mode); chunkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); chunkNo++; } while (getActiveThreads(chunkThreads) > 0) { if (DEBUG) System.out.println("Active Splitfile inserts remaining: " + getActiveThreads(chunkThreads)); mixed.wait(3000); } segmentKeyMaps.add(chunkResults); } int checkNo = 0; for (int i = 0; i < checkFileMaps.size(); i++) { File[] currentFileMap = (File[]) checkFileMaps.get(i); checkThreads = new Thread[currentFileMap.length]; checkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Check: " + checkNo); while (getActiveThreads(checkThreads) >= maxThreads) mixed.wait(5000); checkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, checkResults, threadCount, mode); checkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); checkNo++; } while (getActiveThreads(checkThreads) > 0) { if (DEBUG) System.out.println("Active Checkblock inserts remaining: " + getActiveThreads(checkThreads)); mixed.wait(3000); } checkKeyMaps.add(checkResults); } checkThreads = null; } String redirect = null; { synchronized (fecutils.getClass()) { try { redirect = fecutils.FECMakeMetadata(segmentHeaders, segmentKeyMaps, checkKeyMaps, "Frost"); } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } String[] sortedRedirect = redirect.split("\n"); for (int z = 0; z < sortedRedirect.length; z++) System.out.println(sortedRedirect[z]); int sortStart = -1; int sortEnd = -1; for (int line = 0; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("Document")) { sortStart = line + 1; break; } } for (int line = sortStart; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("End")) { sortEnd = line; break; } } System.out.println("sortStart " + sortStart + " sortEnd " + sortEnd); if (sortStart < sortEnd) Arrays.sort(sortedRedirect, sortStart, sortEnd); redirect = new String(); for (int line = 0; line < sortedRedirect.length; line++) redirect += sortedRedirect[line] + "\n"; System.out.println(redirect); } int tries = 0; String[] result = { "Error", "Error" }; while (!result[0].equals("Success") && !result[0].equals("KeyCollision") && tries < 8) { tries++; try { FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); output = connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, mode); } catch (FcpToolsException e) { if (DEBUG) System.out.println("FcpToolsException " + e); frame1.displayWarning(e.toString()); } catch (UnknownHostException e) { if (DEBUG) System.out.println("UnknownHostException"); frame1.displayWarning(e.toString()); } catch (IOException e) { if (DEBUG) System.out.println("IOException"); frame1.displayWarning(e.toString()); } result = result(output); mixed.wait(3000); if (DEBUG) System.out.println("*****" + result[0] + " " + result[1] + " "); } if ((result[0].equals("Success") || result[0].equals("KeyCollision")) && mode) { try { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); String dirdate = cal.get(Calendar.YEAR) + "."; dirdate += cal.get(Calendar.MONTH) + 1 + "."; dirdate += cal.get(Calendar.DATE); String fileSeparator = System.getProperty("file.separator"); String destination = frame1.keypool + board + fileSeparator + dirdate + fileSeparator; FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); String contentKey = result(connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, false))[1]; String prefix = new String("freenet:"); if (contentKey.startsWith(prefix)) contentKey = contentKey.substring(prefix.length()); FileAccess.writeFile("Already uploaded today", destination + contentKey + ".lck"); } catch (Exception e) { } } return result; }
Code Sample 2:
public static void copyFile(String file1, String file2) { File filedata1 = new java.io.File(file1); if (filedata1.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file1)); try { int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); } catch (IOException ex1) { ex1.printStackTrace(); } finally { out.close(); in.close(); } } catch (Exception ex) { ex.printStackTrace(); } } }
|
11
|
Code Sample 1:
@Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; }
Code Sample 2:
public static File copyFile(File from, File to) throws IOException { FileOutputStream fos = new FileOutputStream(to); FileInputStream fis = new FileInputStream(from); FileChannel foc = fos.getChannel(); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return to; }
|
11
|
Code Sample 1:
@Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", 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:
public static boolean copy(InputStream is, File file) { try { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); is.close(); fos.close(); return true; } catch (Exception e) { System.err.println(e.getMessage()); return false; } }
Code Sample 2:
public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } }
|
11
|
Code Sample 1:
private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } }
Code Sample 2:
public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void initFiles() throws IOException { if (!tempDir.exists()) { if (!tempDir.mkdir()) throw new IOException("Temp dir '' can not be created"); } File tmp = new File(tempDir, TORRENT_FILENAME); if (!tmp.exists()) { FileChannel in = new FileInputStream(torrentFile).getChannel(); FileChannel out = new FileOutputStream(tmp).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } torrentFile = tmp; if (!stateFile.exists()) { FileChannel out = new FileOutputStream(stateFile).getChannel(); int numChunks = metadata.getPieceHashes().size(); ByteBuffer zero = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0 }); for (int i = 0; i < numChunks; i++) { out.write(zero); zero.clear(); } out.close(); } }
|
00
|
Code Sample 1:
public static IChemModel readInChI(URL url) throws CDKException { IChemModel chemModel = new ChemModel(); try { IMoleculeSet moleculeSet = new MoleculeSet(); chemModel.setMoleculeSet(moleculeSet); StdInChIParser parser = new StdInChIParser(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (line.toLowerCase().startsWith("inchi=")) { IAtomContainer atc = parser.parseInchi(line); moleculeSet.addAtomContainer(atc); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new CDKException(e.getMessage()); } return chemModel; }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_THUMBNAIL_PREFIX) + Constants.SERVLET_THUMBNAIL_PREFIX.length() + 1); if (uuid != null && !"".equals(uuid)) { resp.setContentType("image/jpeg"); StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_THUMB/content"); InputStream is = null; if (!Constants.MISSING.equals(uuid)) { is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), true); } else { is = new FileInputStream(new File("images/other/file_not_found.png")); } if (is == null) { return; } ServletOutputStream os = resp.getOutputStream(); try { IOUtils.copyStreams(is, os); } catch (IOException e) { } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { } finally { is = null; } } } resp.setStatus(200); } else { resp.setStatus(404); } }
|
11
|
Code Sample 1:
public boolean isServerAlive(String pStrURL) { boolean isAlive; long t1 = System.currentTimeMillis(); try { URL url = new URL(pStrURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { logger.fine(inputLine); } logger.info("** Connection successful.. **"); in.close(); isAlive = true; } catch (Exception e) { logger.info("** Connection failed.. **"); e.printStackTrace(); isAlive = false; } long t2 = System.currentTimeMillis(); logger.info("Time taken to check connection: " + (t2 - t1) + " ms."); return isAlive; }
Code Sample 2:
protected static boolean isLatestVersion(double myVersion, String referenceAddress) { Scanner scanner = null; try { URL url = new URL(referenceAddress); InputStream iS = url.openStream(); scanner = new Scanner(iS); String firstLine = scanner.nextLine(); double latestVersion = Double.valueOf(firstLine.trim()); double thisVersion = OpenSONAR.VERSION; return thisVersion >= latestVersion; } catch (UnknownHostException e) { System.out.println("Unknown Host!!!"); return false; } catch (Exception e) { System.out.println("Can't decide latest version"); e.printStackTrace(); return false; } }
|
00
|
Code Sample 1:
private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); }
Code Sample 2:
private byte[] getBytesFromUrl(URL url) { ByteArrayOutputStream bais = new ByteArrayOutputStream(); InputStream is = null; try { is = url.openStream(); byte[] byteChunk = new byte[4096]; int n; while ((n = is.read(byteChunk)) > 0) { bais.write(byteChunk, 0, n); } } catch (IOException e) { System.err.printf("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage()); e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return bais.toByteArray(); }
|
00
|
Code Sample 1:
public void alterar(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "update cliente set nome = ?, sexo = ?, cod_cidade = ? where cod_cliente = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, cliente.getNome()); stmt.setString(2, cliente.getSexo()); stmt.setInt(3, cliente.getCidade().getCodCidade()); stmt.setLong(4, cliente.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de alterar dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
Code Sample 2:
public static String getProgramVersion() { String s = "0"; try { URL url; URLConnection urlConn; DataInputStream dis; url = new URL("http://www.dombosfest.org.yu/log/yamiversion.dat"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); dis = new DataInputStream(urlConn.getInputStream()); while ((dis.readUTF()) != null) { s = dis.readUTF(); } dis.close(); } catch (MalformedURLException mue) { System.out.println("mue:" + mue.getMessage()); } catch (IOException ioe) { System.out.println("ioe:" + ioe.getMessage()); } return s; }
|
11
|
Code Sample 1:
public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Code Sample 2:
@Override public void actionPerformed(ActionEvent e) { if (copiedFiles_ != null) { File[] tmpFiles = new File[copiedFiles_.length]; File tmpDir = new File(Settings.getPropertyString(ConstantKeys.project_dir), "tmp/"); tmpDir.mkdirs(); for (int i = copiedFiles_.length - 1; i >= 0; i--) { Frame f = FrameManager.getInstance().getFrameAtIndex(i); try { File in = f.getFile(); File out = new File(tmpDir, f.getFile().getName()); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); tmpFiles[i] = out; } catch (IOException e1) { e1.printStackTrace(); } } try { FrameManager.getInstance().insertFrames(getTable().getSelectedRow(), FrameManager.INSERT_TYPE.MOVE, tmpFiles); } catch (IOException e1) { e1.printStackTrace(); } } }
|
00
|
Code Sample 1:
public static void parseRDFXML(String url, StatementHandler handler) throws IOException { ARP parser = new ARP(); parser.getHandlers().setStatementHandler(handler); URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); InputStream in = null; try { in = conn.getInputStream(); if (encoding == null) parser.load(in, url); else parser.load(new InputStreamReader(in, encoding), url); in.close(); } catch (org.xml.sax.SAXException e) { throw new OntopiaRuntimeException(e); } finally { if (in != null) in.close(); } }
Code Sample 2:
protected GraphicalViewer createGraphicalViewer(Composite parent) { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); GraphicalViewerKeyHandler graphicalViewerKeyHandler = new GraphicalViewerKeyHandler(viewer); KeyHandler parentKeyHandler = graphicalViewerKeyHandler.setParent(getCommonKeyHandler()); viewer.setKeyHandler(parentKeyHandler); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); ContextMenuProvider provider = new TestContextMenuProvider(viewer, getActionRegistry()); viewer.setContextMenu(provider); getSite().registerContextMenu("cubicTestPlugin.editor.contextmenu", provider, viewer); viewer.addDropTargetListener(new DataEditDropTargetListner(((IFileEditorInput) getEditorInput()).getFile().getProject(), viewer)); viewer.addDropTargetListener(new FileTransferDropTargetListener(viewer)); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getContent()); return viewer; }
|
11
|
Code Sample 1:
public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pReader, fw); fw.flush(); fw.close(); pReader.close(); flag = true; } catch (Exception e) { LOG.error("将字符流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; }
Code Sample 2:
public void writeBack(File destinationFile, boolean makeCopy) throws IOException { if (makeCopy) { FileChannel sourceChannel = new java.io.FileInputStream(getFile()).getChannel(); FileChannel destinationChannel = new java.io.FileOutputStream(destinationFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } else { getFile().renameTo(destinationFile); } if (getExifTime() != null && getOriginalTime() != null && !getExifTime().equals(getOriginalTime())) { String adjustArgument = "-ts" + m_dfJhead.format(getExifTime()); ProcessBuilder pb = new ProcessBuilder(m_tm.getJheadCommand(), adjustArgument, destinationFile.getAbsolutePath()); pb.directory(destinationFile.getParentFile()); System.out.println(pb.command().get(0) + " " + pb.command().get(1) + " " + pb.command().get(2)); final Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } }
|
00
|
Code Sample 1:
private static String func(String sf) { int total = 0, temp; String fnctn[] = { "sin", "cos", "tan", "log", "ln", "sqrt", "!" }, temp2 = ""; int pos[] = new int[7]; for (int n = 0; n < fnctn.length; n++) { pos[n] = sf.lastIndexOf(fnctn[n]); } for (int m = 0; m < fnctn.length; m++) { total += pos[m]; } if (total == -7) { return sf; } for (int i = pos.length; i > 1; i--) { for (int j = 0; j < i - 1; j++) { if (pos[j] < pos[j + 1]) { temp = pos[j]; pos[j] = pos[j + 1]; pos[j + 1] = temp; temp2 = fnctn[j]; fnctn[j] = fnctn[j + 1]; fnctn[j + 1] = temp2; } } } if (fnctn[0].equals("sin")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.sine(sf, pos[0], false)); } else { return func(Functions.asin(sf, pos[0], false)); } } else if (fnctn[0].equals("cos")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.cosine(sf, pos[0], false)); } else { return func(Functions.acos(sf, pos[0], false)); } } else if (fnctn[0].equals("tan")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.tangent(sf, pos[0], false)); } else { return func(Functions.atan(sf, pos[0], false)); } } else if (fnctn[0].equals("log")) { return func(Functions.logarithm(sf, pos[0])); } else if (fnctn[0].equals("ln")) { return func(Functions.lnat(sf, pos[0])); } else if (fnctn[0].equals("sqrt")) { return func(Functions.sqroot(sf, pos[0])); } else { return func(Functions.factorial(sf, pos[0])); } }
Code Sample 2:
private static String processStr(String srcStr, String sign) throws NoSuchAlgorithmException, NullPointerException { if (null == srcStr) { throw new java.lang.NullPointerException("��Ҫ���ܵ��ַ�ΪNull"); } MessageDigest digest; String algorithm = "MD5"; String result = ""; digest = MessageDigest.getInstance(algorithm); digest.update(srcStr.getBytes()); byte[] byteRes = digest.digest(); int length = byteRes.length; for (int i = 0; i < length; i++) { result = result + byteHEX(byteRes[i], sign); } return result; }
|
11
|
Code Sample 1:
private String doSearch(String query) { StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("http://boss.yahooapis.com/ysearch/web/v1/").append(query).append("?appid=wGsFV_DV34EwXnC.2Bt_Ql8Kcir_HmrxMzWUF2fv64CA8ha7e4zgudqXFA8K_J4-&format=xml&filter=-porn"); try { URL url = new URL(queryBuilder.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); return safeParseXml(buffer.toString()); } catch (MalformedURLException e) { log.error("The used url is not right : " + queryBuilder.toString(), e); return "The used url is not right."; } catch (IOException e) { log.error("Problem obtaining search results, connection maybe?", e); return "Problem obtaining search results, connection maybe?"; } }
Code Sample 2:
private String getXml(String url) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); String results = null; if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { results = EntityUtils.toString(entity); } else { } } return (results); }
|
00
|
Code Sample 1:
public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("TAudioFileReader.getAudioFileFormat(URL): begin"); } long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED; InputStream inputStream = url.openStream(); AudioFileFormat audioFileFormat = null; try { audioFileFormat = getAudioFileFormat(inputStream, lFileLengthInBytes); } finally { inputStream.close(); } if (TDebug.TraceAudioFileReader) { TDebug.out("TAudioFileReader.getAudioFileFormat(URL): end"); } return audioFileFormat; }
Code Sample 2:
private void createProperty(String objectID, String value, String propertyID, Long userID) throws JspTagException { ClassProperty classProperty = new ClassProperty(new Long(propertyID)); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(new Long(propertyID), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } }
|
00
|
Code Sample 1:
public static boolean copyFile(File source, File dest) throws IOException { int answer = JOptionPane.YES_OPTION; if (dest.exists()) { answer = JOptionPane.showConfirmDialog(null, "File " + dest.getAbsolutePath() + "\n already exists. Overwrite?", "Warning", JOptionPane.YES_NO_OPTION); } if (answer == JOptionPane.NO_OPTION) return false; dest.createNewFile(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } return true; } catch (Exception e) { return false; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Code Sample 2:
public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; }
|
00
|
Code Sample 1:
protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
Code Sample 2:
@Override protected Object doInBackground() throws Exception { ArchiveInputStream bufIn = null; FileOutputStream fileOut = null; try { bufIn = DecompressionWorker.guessStream(fileToExtract); ArchiveEntry curZip = null; int progress = 0; while ((curZip = bufIn.getNextEntry()) != null) { if (!curZip.isDirectory()) { byte[] content = new byte[(int) curZip.getSize()]; fileOut = new FileOutputStream(extractionFile.getAbsolutePath() + File.separator + curZip.getName()); for (int i = 0; i < content.length; i++) { fileOut.write(content[i]); } publish(new Integer(progress)); progress++; } } } finally { if (bufIn != null) { bufIn.close(); } } return null; }
|
00
|
Code Sample 1:
public void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
Code Sample 2:
private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
|
11
|
Code Sample 1:
@Override public void run() { try { if (LOG.isDebugEnabled()) { LOG.debug("Backupthread started"); } if (_file.exists()) { _file.delete(); } final ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(_file)); zOut.setLevel(9); final File xmlFile = File.createTempFile("mp3db", ".xml"); final OutputStream ost = new FileOutputStream(xmlFile); final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(ost, "UTF-8"); writer.writeStartDocument("UTF-8", "1.0"); writer.writeCharacters("\n"); writer.writeStartElement("mp3db"); writer.writeAttribute("version", Integer.toString(Main.ENGINEVERSION)); final MediafileDAO mfDAO = new MediafileDAO(); final AlbumDAO aDAO = new AlbumDAO(); final CdDAO cdDAO = new CdDAO(); final CoveritemDAO ciDAO = new CoveritemDAO(); int itemCount = 0; try { itemCount += mfDAO.getCount(); itemCount += aDAO.getCount(); itemCount += cdDAO.getCount(); itemCount += ciDAO.getCount(); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, itemCount)); } catch (final Exception e) { LOG.error("Error getting size", e); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, -1)); } int cdCounter = 0; int mediafileCounter = 0; int albumCounter = 0; int coveritemCounter = 0; int counter = 0; final List<CdIf> data = cdDAO.getCdsOrderById(); if (data.size() > 0) { final Map<Integer, Integer> albums = new HashMap<Integer, Integer>(); final Iterator<CdIf> it = data.iterator(); while (it.hasNext() && !_break) { final CdIf cd = it.next(); final Integer cdId = Integer.valueOf(cdCounter++); writer.writeStartElement(TypeConstants.XML_CD); exportCd(writer, cd, cdId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final List<MediafileIf> files = cd.getMediafiles(); final Iterator<MediafileIf> mfit = files.iterator(); MediafileIf mf; while (mfit.hasNext() && !_break) { mf = mfit.next(); final Integer mfId = Integer.valueOf(mediafileCounter++); writer.writeStartElement(TypeConstants.XML_MEDIAFILE); exportMediafile(writer, mf, mfId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final AlbumIf a = mf.getAlbum(); if (a != null) { Integer inte; if (albums.containsKey(a.getAid())) { inte = albums.get(a.getAid()); writeLink(writer, TypeConstants.XML_ALBUM, inte); } else { inte = Integer.valueOf(albumCounter++); writer.writeStartElement(TypeConstants.XML_ALBUM); exportAlbum(writer, a, inte); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); albums.put(a.getAid(), inte); if (a.hasCoveritems() && !_break) { final List<CoveritemIf> covers = a.getCoveritems(); final Iterator<CoveritemIf> coit = covers.iterator(); while (coit.hasNext() && !_break) { final Integer coveritemId = Integer.valueOf(coveritemCounter++); exportCoveritem(writer, zOut, coit.next(), coveritemId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); } } writer.writeEndElement(); } GenericDAO.getEntityManager().close(); } writer.writeEndElement(); } writer.writeEndElement(); writer.flush(); it.remove(); GenericDAO.getEntityManager().close(); } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); ost.flush(); ost.close(); if (_break) { zOut.close(); _file.delete(); } else { zOut.putNextEntry(new ZipEntry("mp3.xml")); final InputStream xmlIn = FileUtils.openInputStream(xmlFile); IOUtils.copy(xmlIn, zOut); xmlIn.close(); zOut.close(); } xmlFile.delete(); fireStatusEvent(new StatusEvent(this, StatusEventType.FINISH)); } catch (final Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Error backup database", e); } fireStatusEvent(new StatusEvent(this, e, "")); _messenger.fireMessageEvent(new MessageEvent(this, "ERROR", MessageEventTypeEnum.ERROR, GuiStrings.getInstance().getString("error.backup"), e)); } }
Code Sample 2:
public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
|
00
|
Code Sample 1:
private File copyFromURL(URL url, String dir) throws IOException { File urlFile = new File(url.getFile()); File dest = new File(dir, urlFile.getName()); logger.log("Extracting " + urlFile.getName() + " to " + dir + "..."); FileOutputStream os = new FileOutputStream(dest); InputStream is = url.openStream(); byte data[] = new byte[4096]; int ct; while ((ct = is.read(data)) >= 0) os.write(data, 0, ct); is.close(); os.close(); logger.log("ok\n"); return dest; }
Code Sample 2:
public HttpUrlConnectionCall(HttpClientHelper helper, String method, String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); if (requestUri.startsWith("http")) { URL url = new URL(requestUri); this.connection = (HttpURLConnection) url.openConnection(); int majorVersionNumber = Engine.getJavaMajorVersion(); int minorVersionNumber = Engine.getJavaMinorVersion(); if ((majorVersionNumber > 1) || (majorVersionNumber == 1 && minorVersionNumber >= 5)) { this.connection.setConnectTimeout(getHelper().getConnectTimeout()); this.connection.setReadTimeout(getHelper().getReadTimeout()); } this.connection.setAllowUserInteraction(getHelper().isAllowUserInteraction()); this.connection.setDoOutput(hasEntity); this.connection.setInstanceFollowRedirects(getHelper().isFollowRedirects()); this.connection.setUseCaches(getHelper().isUseCaches()); this.responseHeadersAdded = false; setConfidential(this.connection instanceof HttpsURLConnection); } else { throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here"); } }
|
11
|
Code Sample 1:
public static void zip() throws Exception { System.out.println("zip()"); ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(new File("/zip/myzip.zip"))); ZipEntry entry = new ZipEntry("asdf.script"); zipout.putNextEntry(entry); byte buffer[] = new byte[BLOCKSIZE]; FileInputStream in = new FileInputStream(new File("/zip/asdf.script")); for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length); in.close(); zipout.closeEntry(); zipout.close(); }
Code Sample 2:
public static boolean writeFile(HttpServletResponse resp, File reqFile) { boolean retVal = false; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(reqFile)); IOUtils.copy(in, resp.getOutputStream()); logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath()); } catch (FileNotFoundException e) { logger.error("Resource not found: " + reqFile.getAbsolutePath()); } catch (IOException e) { logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()), e); } finally { IOUtils.closeQuietly(in); } return retVal; }
|
00
|
Code Sample 1:
public synchronized List<AnidbSearchResult> getAnimeTitles() throws Exception { URL url = new URL("http", host, "/api/animetitles.dat.gz"); ResultCache cache = getCache(); @SuppressWarnings("unchecked") List<AnidbSearchResult> anime = (List) cache.getSearchResult(null, Locale.ROOT); if (anime != null) { return anime; } Pattern pattern = Pattern.compile("^(?!#)(\\d+)[|](\\d)[|]([\\w-]+)[|](.+)$"); Map<Integer, String> primaryTitleMap = new HashMap<Integer, String>(); Map<Integer, Map<String, String>> officialTitleMap = new HashMap<Integer, Map<String, String>>(); Map<Integer, Map<String, String>> synonymsTitleMap = new HashMap<Integer, Map<String, String>>(); Scanner scanner = new Scanner(new GZIPInputStream(url.openStream()), "UTF-8"); try { while (scanner.hasNextLine()) { Matcher matcher = pattern.matcher(scanner.nextLine()); if (matcher.matches()) { int aid = Integer.parseInt(matcher.group(1)); String type = matcher.group(2); String language = matcher.group(3); String title = matcher.group(4); if (type.equals("1")) { primaryTitleMap.put(aid, title); } else if (type.equals("2") || type.equals("4")) { Map<Integer, Map<String, String>> titleMap = (type.equals("4") ? officialTitleMap : synonymsTitleMap); Map<String, String> languageTitleMap = titleMap.get(aid); if (languageTitleMap == null) { languageTitleMap = new HashMap<String, String>(); titleMap.put(aid, languageTitleMap); } languageTitleMap.put(language, title); } } } } finally { scanner.close(); } anime = new ArrayList<AnidbSearchResult>(primaryTitleMap.size()); for (Entry<Integer, String> entry : primaryTitleMap.entrySet()) { Map<String, String> localizedTitles = new HashMap<String, String>(); if (synonymsTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(synonymsTitleMap.get(entry.getKey())); } if (officialTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(officialTitleMap.get(entry.getKey())); } anime.add(new AnidbSearchResult(entry.getKey(), entry.getValue(), localizedTitles)); } return cache.putSearchResult(null, Locale.ROOT, anime); }
Code Sample 2:
@Test public void testDoGet() throws Exception { HttpHost targetHost = new HttpHost("localhost", 8080, "http"); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("vince", "test56")); try { HttpGet httpget = new HttpGet("http://localhost:8080/objectwiz/api?invokeFacetOperation=createNewEntity&objectClassName=org.objectwiz.testapp.jee5.addressbook.Person&applicationName=addressbook&methodReference=persist(E)&args=(lastname=toto)"); System.out.println("executing request " + httpget.getURI()); HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header h = headers[i]; System.out.println(h.getName() + "/" + h.getValue()); } assertEquals(response.getStatusLine().getStatusCode(), 200); System.out.println("----------------------------------------"); if (entity != null) { System.out.println("response content length" + entity.getContentLength()); System.out.println(entity.getContentType().getName() + "/" + entity.getContentType().getValue()); } httpget.abort(); } finally { client.getConnectionManager().shutdown(); } }
|
11
|
Code Sample 1:
public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; }
|
11
|
Code Sample 1:
public byte process(ProcessorContext<PublishRequest> context) throws InterruptedException, ProcessorException { logger.info("MapTileChacheTask:process"); PublishRequest req = context.getItem().getEntity(); if (StringUtils.isEmpty(req.getBackMap())) return TaskState.STATE_TILE_CACHED; final PublicMapPost post; final GenericDAO<PublicMapPost> postDao = DAOFactory.createDAO(PublicMapPost.class); try { ReadOnlyTransaction.beginTransaction(); } catch (DatabaseException e) { logger.error("error", e); throw new ProcessorException(e); } int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); post = postDao.findUniqueByCriteria(Expression.eq("guid", req.getPostGuid())); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(post.getSWLat(), post.getSWLon()), new LatLngPoint(post.getNELat(), post.getNELon())); 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); } } try { for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) throw new IllegalAccessException("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); } else throw new IllegalStateException("opened stream is null"); } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 100 == 0) { logger.info(numCachedTiles + " tiles cached"); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } } catch (ProcessorException e) { logger.error("map tile caching has failed: ", e); throw e; } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } finally { ReadOnlyTransaction.closeTransaction(); logger.info(numCachedTiles + " tiles cached"); } return TaskState.STATE_TILE_CACHED; }
Code Sample 2:
public GetMessages(String messageType) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMessages"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "messages.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&messagetype=" + messageType + "&filename=" + URLEncoder.encode(username, "UTF-8") + "messages.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("message"); int num = nodelist.getLength(); messages = new String[num][7]; for (int i = 0; i < num; i++) { messages[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageid")); messages[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "subject")); messages[i][2] = (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "firstname"))) + " " + (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "lastname"))); messages[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagedatetime")); messages[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagefrom")); messages[i][5] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageto")); messages[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
|
11
|
Code Sample 1:
@Override public RServiceResponse execute(final NexusServiceRequest inData) throws NexusServiceException { final RServiceRequest data = (RServiceRequest) inData; final RServiceResponse retval = new RServiceResponse(); final StringBuilder result = new StringBuilder("R service call results:\n"); RSession session; RConnection connection = null; try { result.append("Session Attachment: \n"); final byte[] sessionBytes = data.getSession(); if (sessionBytes != null && sessionBytes.length > 0) { session = RUtils.getInstance().bytesToSession(sessionBytes); result.append(" attaching to " + session + "\n"); connection = session.attach(); } else { result.append(" creating new session\n"); connection = new RConnection(data.getServerAddress()); } result.append("Input Parameters: \n"); for (String attributeName : data.getInputVariables().keySet()) { final Object parameter = data.getInputVariables().get(attributeName); if (parameter instanceof URI) { final FileObject file = VFS.getManager().resolveFile(((URI) parameter).toString()); final RFileOutputStream ros = connection.createFile(file.getName().getBaseName()); IOUtils.copy(file.getContent().getInputStream(), ros); connection.assign(attributeName, file.getName().getBaseName()); } else { connection.assign(attributeName, RUtils.getInstance().convertToREXP(parameter)); } result.append(" " + parameter.getClass().getSimpleName() + " " + attributeName + "=" + parameter + "\n"); } final REXP rExpression = connection.eval(RUtils.getInstance().wrapCode(data.getCode().replace('\r', '\n'))); result.append("Execution results:\n" + rExpression.asString() + "\n"); if (rExpression.isNull() || rExpression.asString().startsWith("Error")) { retval.setErr(rExpression.asString()); throw new NexusServiceException("R error: " + rExpression.asString()); } result.append("Output Parameters:\n"); final String[] rVariables = connection.eval("ls();").asStrings(); for (String varname : rVariables) { final String[] rVariable = connection.eval("class(" + varname + ")").asStrings(); if (rVariable.length == 2 && "file".equals(rVariable[0]) && "connection".equals(rVariable[1])) { final String rFileName = connection.eval("showConnections(TRUE)[" + varname + "]").asString(); result.append(" R File ").append(varname).append('=').append(rFileName).append('\n'); final RFileInputStream rInputStream = connection.openFile(rFileName); final File file = File.createTempFile("nexus-" + data.getRequestId(), ".dat"); IOUtils.copy(rInputStream, new FileOutputStream(file)); retval.getOutputVariables().put(varname, file.getCanonicalFile().toURI()); } else { final Object varvalue = RUtils.getInstance().convertREXP(connection.eval(varname)); retval.getOutputVariables().put(varname, varvalue); final String printValue = varvalue == null ? "null" : varvalue.getClass().isArray() ? Arrays.asList(varvalue).toString() : varvalue.toString(); result.append(" ").append(varvalue == null ? "" : varvalue.getClass().getSimpleName()).append(' ').append(varname).append('=').append(printValue).append('\n'); } } } catch (ClassNotFoundException cnfe) { retval.setErr(cnfe.getMessage()); LOGGER.error("Rserve Exception", cnfe); } catch (RserveException rse) { retval.setErr(rse.getMessage()); LOGGER.error("Rserve Exception", rse); } catch (REXPMismatchException rme) { retval.setErr(rme.getMessage()); LOGGER.error("REXP Mismatch Exception", rme); } catch (IOException rme) { retval.setErr(rme.getMessage()); LOGGER.error("IO Exception copying file ", rme); } finally { result.append("Session Detachment:\n"); if (connection != null) { RSession outSession; if (retval.isKeepSession()) { try { outSession = connection.detach(); } catch (RserveException e) { LOGGER.debug("Error detaching R session", e); outSession = null; } } else { outSession = null; } final boolean close = outSession == null; if (!close) { retval.setSession(RUtils.getInstance().sessionToBytes(outSession)); result.append(" suspended session for later use\n"); } connection.close(); retval.setSession(null); result.append(" session closed.\n"); } } retval.setOut(result.toString()); return retval; }
Code Sample 2:
public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
|
00
|
Code Sample 1:
public ArrayList parseFile(File newfile) throws IOException { String s; String firstName; String header; String name = null; Integer PVLoggerID = new Integer(0); String[] tokens; int nvalues = 0; double num1, num2, num3; double xoffset = 1.0; double xdelta = 1.0; double yoffset = 1.0; double ydelta = 1.0; double zoffset = 1.0; double zdelta = 1.0; boolean readfit = false; boolean readraw = false; boolean zerodata = false; boolean baddata = false; boolean harpdata = false; ArrayList fitparams = new ArrayList(); ArrayList xraw = new ArrayList(); ArrayList yraw = new ArrayList(); ArrayList zraw = new ArrayList(); ArrayList sraw = new ArrayList(); ArrayList sxraw = new ArrayList(); ArrayList syraw = new ArrayList(); ArrayList szraw = new ArrayList(); URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; firstName = (String) tokens[0]; if (((String) tokens[0]).length() == 0) { readraw = false; readfit = false; continue; } if ((nvalues == 4) && (!firstName.startsWith("---"))) { if ((Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.)) { zerodata = true; } else { zerodata = false; } if (tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")) { baddata = true; } else { baddata = false; } } if (firstName.startsWith("start")) { header = s; } if (firstName.indexOf("WS") > 0) { if (name != null) { dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); } name = tokens[0]; readraw = false; readfit = false; zerodata = false; baddata = false; harpdata = false; fitparams.clear(); xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); } if (firstName.startsWith("Area")) ; if (firstName.startsWith("Ampl")) ; if (firstName.startsWith("Mean")) ; if (firstName.startsWith("Sigma")) { fitparams.add(new Double(Double.parseDouble(tokens[3]))); fitparams.add(new Double(Double.parseDouble(tokens[1]))); fitparams.add(new Double(Double.parseDouble(tokens[5]))); } if (firstName.startsWith("Offset")) ; if (firstName.startsWith("Slope")) ; if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Raw"))) { readraw = true; continue; } if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Fit"))) { readfit = true; continue; } if ((firstName.contains("Harp"))) { xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); harpdata = true; readraw = true; name = tokens[0]; continue; } if (firstName.startsWith("---")) continue; if (harpdata == true) { if (((String) tokens[0]).length() != 0) { if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } else { sxraw.add(new Double(Double.parseDouble(tokens[0]))); xraw.add(new Double(Double.parseDouble(tokens[1]))); syraw.add(new Double(Double.parseDouble(tokens[2]))); yraw.add(new Double(Double.parseDouble(tokens[3]))); szraw.add(new Double(Double.parseDouble(tokens[4]))); zraw.add(new Double(Double.parseDouble(tokens[5]))); } } continue; } if (readraw && (!zerodata) && (!baddata)) { sraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); sxraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); syraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); szraw.add(new Double(Double.parseDouble(tokens[0]))); yraw.add(new Double(Double.parseDouble(tokens[1]))); zraw.add(new Double(Double.parseDouble(tokens[2]))); xraw.add(new Double(Double.parseDouble(tokens[3]))); } if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } } dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); wiredata.add((Integer) PVLoggerID); return wiredata; }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
public String generateDigest(String password, String saltHex, String algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsIgnoreCase("crypt")) { return "{CRYPT}" + UnixCrypt.crypt(password); } else if (algorithm.equalsIgnoreCase("sha")) { algorithm = "SHA-1"; } else if (algorithm.equalsIgnoreCase("md5")) { algorithm = "MD5"; } MessageDigest msgDigest = MessageDigest.getInstance(algorithm); byte[] salt = {}; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (algorithm.startsWith("SHA")) { label = (salt.length > 0) ? "{SSHA}" : "{SHA}"; } else if (algorithm.startsWith("MD5")) { label = (salt.length > 0) ? "{SMD5}" : "{MD5}"; } msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt))); return digest.toString(); }
Code Sample 2:
public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
|
11
|
Code Sample 1:
private static byte[] sha2(String... data) { byte[] digest = new byte[32]; StringBuilder buffer = new StringBuilder(); for (String s : data) { buffer.append(s); } MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { assert false; } sha256.update(buffer.toString().getBytes()); try { sha256.digest(digest, 0, digest.length); } catch (DigestException ex) { assert false; } return digest; }
Code Sample 2:
public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: MD5AttachHandler::invoke"); try { Message msg = msgContext.getRequestMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope(); org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody(); org.w3c.dom.Element sbElement = sbe.getAsDOM(); org.w3c.dom.Node n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n; String href = paramElement.getAttribute(soapConstants.getAttrHref()); org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils.getActivationDataHandler(ap); org.w3c.dom.Node timeNode = paramElement.getFirstChild(); long startTime = -1; if (timeNode != null && timeNode instanceof org.w3c.dom.Text) { String startTimeStr = ((org.w3c.dom.Text) timeNode).getData(); startTime = Long.parseLong(startTimeStr); } long receivedTime = System.currentTimeMillis(); long elapsedTime = -1; if (startTime > 0) elapsedTime = receivedTime - startTime; String elapsedTimeStr = elapsedTime + ""; java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.io.InputStream attachmentStream = dh.getInputStream(); int bread = 0; byte[] buf = new byte[64 * 1024]; do { bread = attachmentStream.read(buf); if (bread > 0) { md.update(buf, 0, bread); } } while (bread > -1); attachmentStream.close(); buf = null; String contentType = dh.getContentType(); if (contentType != null && contentType.length() != 0) { md.update(contentType.getBytes("US-ASCII")); } sbe = env.getFirstBody(); sbElement = sbe.getAsDOM(); n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; paramElement = (org.w3c.dom.Element) n; String MD5String = org.apache.axis.encoding.Base64.encode(md.digest()); String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String; paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata)); sbe = new org.apache.axis.message.SOAPBodyElement(sbElement); env.clearBody(); env.addBodyElement(sbe); msg = new Message(env); msgContext.setResponseMessage(msg); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } log.debug("Exit: MD5AttachHandler::invoke"); }
|
00
|
Code Sample 1:
private static void checkForUpdates() { LOGGER.debug("Checking for Updates"); new Thread() { @Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (lastVersion.equals(getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } } }.start(); }
Code Sample 2:
public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; }
|
00
|
Code Sample 1:
private static void getFileFtp(String user, String password, String host, int port, String fileName, String location) throws Exception { Log.info("\nretrieve " + fileName + NEW_LINE); FTPClient client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("FTP fail to connect"); } if (!client.login(user, password)) { throw new Exception("FTP fail to login"); } try { File locationFile = new File(location); File dest = new File(locationFile, fileName); if (dest.exists()) { dest.delete(); } else { locationFile.mkdirs(); } boolean status = client.changeWorkingDirectory("/"); Log.info("chdir-status:" + status + NEW_LINE); client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.enterLocalActiveMode(); InputStream in = client.retrieveFileStream(fileName); if (in == null) { Log.error("Input stream is null\n"); throw new Exception("Fail to retrieve file " + fileName); } Thread.sleep(3000); saveInputStreamToFile(in, new File(location, fileName)); } finally { client.disconnect(); } }
Code Sample 2:
public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
|
00
|
Code Sample 1:
public boolean limpiarContrincantexRonda(jugadorxDivxRonda unjxdxr) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = 0 " + " WHERE idJugxDivxRnd = " + unjxdxr.getIdJugxDivxRnd(); 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 boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
|
11
|
Code Sample 1:
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; }
Code Sample 2:
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!"); }
|
11
|
Code Sample 1:
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) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; }
|
00
|
Code Sample 1:
public static File getFileFromURL(URL url) { File tempFile; BufferedInputStream in = null; BufferedOutputStream out = null; try { String tempDir = System.getProperty("java.io.tmpdir", "."); tempFile = File.createTempFile("xxindex", ".tmp", new File(tempDir)); tempFile.deleteOnExit(); InputStream is = url.openStream(); in = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(tempFile); out = new BufferedOutputStream(fos); byte[] b = new byte[1]; while (in.read(b) >= 0) { out.write(b); } logger.debug(url + " written to local file " + tempFile.getAbsolutePath()); } catch (IOException e) { throw new IllegalStateException("Could not create local file for URL: " + url, e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { } } return tempFile; }
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:
public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
Code Sample 2:
private List<Document> storeDocuments(List<Document> documents) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); List<Document> newDocuments = new ArrayList<Document>(); try { session.beginTransaction(); Preference preference = new PreferenceModel(); preference = (Preference) preference.doList(preference).get(0); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); if (documents != null && !documents.isEmpty()) { for (Iterator<Document> iter = documents.iterator(); iter.hasNext(); ) { Document document = iter.next(); if (AppConstants.STATUS_ACTIVE.equals(document.getStatus())) { try { document = (Document) preAdd(document, getParams()); File fileIn = new File(preference.getScanLocation() + File.separator + document.getName()); File fileOut = new File(preference.getStoreLocation() + File.separator + document.getName()); FileInputStream in = new FileInputStream(fileIn); FileOutputStream out = new FileOutputStream(fileOut); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); document.doAdd(document); boolean isDeleted = fileIn.delete(); System.out.println("Deleted scan folder file: " + document.getName() + ":" + isDeleted); if (isDeleted) { document.setStatus(AppConstants.STATUS_PROCESSING); int uploadCount = 0; if (document.getUploadCount() != null) { uploadCount = document.getUploadCount(); } uploadCount++; document.setUploadCount(uploadCount); newDocuments.add(document); } } catch (Exception add_ex) { add_ex.printStackTrace(); } } else if (AppConstants.STATUS_PROCESSING.equals(document.getStatus())) { int uploadCount = document.getUploadCount(); if (uploadCount < 5) { uploadCount++; document.setUploadCount(uploadCount); System.out.println("increase upload count: " + document.getName() + ":" + uploadCount); newDocuments.add(document); } else { System.out.println("delete from documents list: " + document.getName()); } } else if (AppConstants.STATUS_INACTIVE.equals(document.getStatus())) { document.setFixFlag(AppConstants.FLAG_NO); newDocuments.add(document); } } } } catch (Exception ex) { ex.printStackTrace(); } return newDocuments; }
|
00
|
Code Sample 1:
private InputStream getDomainMap() { String domainMap = Configuration.getString(MAPPING_KEY); InputStream is = new StringBufferInputStream(domainMap); if ("".equals(domainMap)) { try { URL url = getClass().getResource(XML_FILE_NAME).toURI().toURL(); is = url.openStream(); } catch (URISyntaxException e) { LOG.warn("Could not find domainmapping file", e); } catch (MalformedURLException e) { LOG.warn("Could not find domainmapping file", e); } catch (IOException e) { LOG.warn("Error reading/fetching domain map", e); } } return is; }
Code Sample 2:
private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; }
|
11
|
Code Sample 1:
@Before public void BeforeTheTest() throws Exception { URL url = ProfileParserTest.class.getClassLoader().getResource("ca/uhn/hl7v2/conf/parser/tests/example_ack.xml"); URLConnection conn = url.openConnection(); InputStream instream = conn.getInputStream(); if (instream == null) throw new Exception("can't find the xml file"); BufferedReader in = new BufferedReader(new InputStreamReader(instream)); int tmp = 0; StringBuffer buf = new StringBuffer(); while ((tmp = in.read()) != -1) { buf.append((char) tmp); } profileString = buf.toString(); }
Code Sample 2:
private boolean loadSymbol(QuoteCache quoteCache, Symbol symbol, TradingDate startDate, TradingDate endDate) { boolean success = true; String URLString = constructURL(symbol, startDate, endDate); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url; url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; while ((line = bufferedInput.readLine()) != null) { Class cl = null; Constructor cnst = null; QuoteFilter filter = null; try { cl = Class.forName("org.mov.quote." + name + "QuoteFilter"); try { cnst = cl.getConstructor(new Class[] { Symbol.class }); } catch (SecurityException e2) { e2.printStackTrace(); } catch (NoSuchMethodException e2) { e2.printStackTrace(); } try { filter = (QuoteFilter) cnst.newInstance(new Object[] { symbol }); } catch (IllegalArgumentException e3) { e3.printStackTrace(); } catch (InstantiationException e3) { e3.printStackTrace(); } catch (IllegalAccessException e3) { e3.printStackTrace(); } catch (InvocationTargetException e3) { e3.printStackTrace(); } } catch (ClassNotFoundException e1) { e1.printStackTrace(); } Quote quote = filter.toQuote(line); if (quote != null) quoteCache.load(quote); } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); success = false; } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); success = false; } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); success = false; } catch (FileNotFoundException e) { } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); success = false; } return success; }
|
00
|
Code Sample 1:
public void doFilter(final ServletRequest arg0, final ServletResponse arg1, final FilterChain arg2) throws IOException, ServletException { if (!this.init) { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter not initialized."); return; } if (this.mainFilter != null) { try { URL url = this.context.getResource("/WEB-INF/classes/log4j.properties"); URLConnection uc = url.openConnection(); if (uc.getLastModified() != lastLoadLog4j) { lastLoadLog4j = uc.getLastModified(); try { uc.getInputStream().close(); } catch (Exception ignore) { } PropertyConfigurator.configure(url); } else { try { uc.getInputStream().close(); } catch (Exception ignore) { } } } catch (final Exception e) { } this.mainFilter.doFilter(arg0, arg1); } else { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter bad setup."); } }
Code Sample 2:
public void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } }
|
00
|
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:
private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; }
|
11
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("LOAD")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (chooser.showOpenDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(file)); ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); int read = is.read(); while (read != -1) { bos.write(read); read = is.read(); } is.close(); _changed = true; setImage(bos.toByteArray()); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("SAVE")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (_data != null && chooser.showSaveDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); os.write(_data); os.flush(); os.close(); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("DELETE")) { if (_data != null) { int result = JOptionPane.showConfirmDialog(getTopLevelAncestor(), GuiStrings.getString("message.removeimg"), GuiStrings.getString("title.confirm"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { removeImage(); _changed = true; } } } }
Code Sample 2:
public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { final ServletOutputStream outputStream = res.getOutputStream(); if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; if (ByteArrayInputStream.class.isAssignableFrom(r.getClass())) res.addHeader("Content-Length", Integer.toString(in.available())); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } outputStream.flush(); } }
|
11
|
Code Sample 1:
private boolean authenticateWithServer(String user, String password) { Object o; String response; byte[] dataKey; try { o = objectIn.readObject(); if (o instanceof String) { response = (String) o; Debug.netMsg("Connected to JFritz Server: " + response); if (!response.equals("JFRITZ SERVER 1.1")) { Debug.netMsg("Unkown Server version, newer JFritz protocoll version?"); Debug.netMsg("Canceling login attempt!"); } objectOut.writeObject(user); objectOut.flush(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.DECRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(desCipher); if (o instanceof byte[]) { dataKey = (byte[]) o; desKeySpec = new DESKeySpec(dataKey); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealed_ok = new SealedObject("OK", outCipher); objectOut.writeObject(sealed_ok); SealedObject sealed_response = (SealedObject) objectIn.readObject(); o = sealed_response.getObject(inCipher); if (o instanceof String) { if (o.equals("OK")) { return true; } else { Debug.netMsg("Server sent wrong string as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong object as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong type for data key!"); } } } catch (ClassNotFoundException e) { Debug.error("Server authentication response invalid!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (EOFException e) { Debug.error("Server closed Stream unexpectedly!"); Debug.error(e.toString()); e.printStackTrace(); } catch (SocketTimeoutException e) { Debug.error("Read timeout while authenticating with server!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.error("Error reading response during authentication!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IllegalBlockSizeException e) { Debug.error("Illegal block size exception!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.error("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return false; }
Code Sample 2:
public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
00
|
Code Sample 1:
public static void loadFile(final URL url, final StringBuffer buffer) throws IOException { InputStream in = null; BufferedReader dis = null; try { in = url.openStream(); dis = new BufferedReader(new InputStreamReader(in)); int i; while ((i = dis.read()) != -1) { buffer.append((char) i); } } finally { closeStream(in); closeReader(dis); } }
Code Sample 2:
@Test public void testCopy() throws IOException { final byte[] input = { 0x00, 0x01, 0x7F, 0x03, 0x40 }; final byte[] verification = input.clone(); Assert.assertNotSame("Expecting verification to be a new array.", input, verification); final ByteArrayInputStream in = new ByteArrayInputStream(input); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); final byte[] output = out.toByteArray(); Assert.assertTrue("Expecting input to be unchanged.", Arrays.equals(verification, input)); Assert.assertTrue("Expecting output to be like input.", Arrays.equals(verification, output)); Assert.assertNotSame("Expecting output to be a new array.", input, output); Assert.assertNotSame("Expecting output to be a new array.", verification, output); }
|
11
|
Code Sample 1:
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) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.