label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } Code Sample 2: private static boolean copyFile(File srcFile, File tagFile) throws IOException { if (srcFile == null || tagFile == null) { return false; } int length = 2097152; FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(tagFile); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); int i = 0; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); break; } if ((inC.size() - inC.position()) < 20971520) length = (int) (inC.size() - inC.position()); else length = 20971520; inC.transferTo(inC.position(), length, outC); inC.position(inC.position() + length); i++; } return true; }
00
Code Sample 1: public static String computeDigest(String str, String alg) { MessageDigest currentAlgorithm = null; try { currentAlgorithm = MessageDigest.getInstance(alg); } catch (NoSuchAlgorithmException e) { return str; } currentAlgorithm.reset(); currentAlgorithm.update(str.getBytes()); byte[] hash = currentAlgorithm.digest(); String d = ""; int usbyte = 0; for (int i = 0; i < hash.length; i++) { usbyte = hash[i] & 0xFF; if (usbyte < 16) d += "0" + Integer.toHexString(usbyte); else d += Integer.toHexString(usbyte); } return d.toUpperCase(); } Code Sample 2: private void handleNodeDown(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_NODE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleNodeDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { String ipAddr = activeSvcsRS.getString(1); long serviceID = activeSvcsRS.getLong(2); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleNodeDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleNodeDown: Recording outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID); } catch (SQLException se) { log.warn("Rolling back transaction, nodeDown could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'nodeDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
11
Code Sample 1: public static void main(String[] args) { String command = "java -jar "; String linkerJarPath = ""; String path = ""; String osName = System.getProperty("os.name"); String temp = Launcher.class.getResource("").toString(); int index = temp.indexOf(".jar"); int start = index - 1; while (Character.isLetter(temp.charAt(start))) { start--; } String jarName = temp.substring(start + 1, index + 4); System.out.println(jarName); if (osName.startsWith("Linux")) { temp = temp.substring(temp.indexOf("/"), temp.indexOf(jarName)); } else if (osName.startsWith("Windows")) { temp = temp.substring(temp.indexOf("file:") + 5, temp.indexOf(jarName)); } else { System.exit(0); } path = path + temp; try { path = java.net.URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File dir = new File(path); File[] files = dir.listFiles(); String exeJarName = null; for (File f : files) { if (f.getName().endsWith(".jar") && !f.getName().startsWith(jarName)) { exeJarName = f.getName(); break; } } if (exeJarName == null) { System.out.println("no exefile"); System.exit(0); } linkerJarPath = path + exeJarName; String pluginDirPath = path + "plugin" + File.separator; File[] plugins = new File(pluginDirPath).listFiles(); StringBuffer pluginNames = new StringBuffer(""); for (File plugin : plugins) { if (plugin.getAbsolutePath().endsWith(".jar")) { pluginNames.append("plugin/" + plugin.getName() + " "); } } String libDirPath = path + "lib" + File.separator; File[] libs = new File(libDirPath).listFiles(); StringBuffer libNames = new StringBuffer(""); for (File lib : libs) { if (lib.getAbsolutePath().endsWith(".jar")) { libNames.append("lib/" + lib.getName() + " "); } } try { JarFile jarFile = new JarFile(linkerJarPath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { manifest = new Manifest(); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Class-Path", pluginNames.toString() + libNames.toString()); String backupFile = linkerJarPath + "back"; FileInputStream copyInput = new FileInputStream(linkerJarPath); FileOutputStream copyOutput = new FileOutputStream(backupFile); byte[] buffer = new byte[4096]; int s; while ((s = copyInput.read(buffer)) > -1) { copyOutput.write(buffer, 0, s); } copyOutput.flush(); copyOutput.close(); copyInput.close(); JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(linkerJarPath), manifest); JarInputStream jarIn = new JarInputStream(new FileInputStream(backupFile)); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } jarOut.flush(); jarOut.close(); jarIn.close(); File file = new File(backupFile); if (file.exists()) { file.delete(); } } catch (IOException e1) { e1.printStackTrace(); } try { if (System.getProperty("os.name").startsWith("Linux")) { Runtime runtime = Runtime.getRuntime(); String[] commands = new String[] { "java", "-jar", path + exeJarName }; runtime.exec(commands); } else { path = path.substring(1); command = command + "\"" + path + exeJarName + "\""; System.out.println(command); Runtime.getRuntime().exec(command); } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: private static void readFileEntry(Zip64File zip64File, FileEntry fileEntry, File destFolder) { FileOutputStream fileOut; File target = new File(destFolder, fileEntry.getName()); File targetsParent = target.getParentFile(); if (targetsParent != null) { targetsParent.mkdirs(); } try { fileOut = new FileOutputStream(target); log.info("[readFileEntry] writing entry: " + fileEntry.getName() + " to file: " + target.getAbsolutePath()); EntryInputStream entryReader = zip64File.openEntryInputStream(fileEntry.getName()); IOUtils.copyLarge(entryReader, fileOut); entryReader.close(); fileOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ZipException e) { log.warning("ATTENTION PLEASE: Some strange, but obviously not serious ZipException occured! Extracted file '" + target.getName() + "' anyway! So don't Panic!" + "\n"); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public final void copyFile(final File fromFile, final File toFile) throws IOException { this.createParentPathIfNeeded(toFile); final FileChannel sourceChannel = new FileInputStream(fromFile).getChannel(); final FileChannel targetChannel = new FileOutputStream(toFile).getChannel(); final long sourceFileSize = sourceChannel.size(); sourceChannel.transferTo(0, sourceFileSize, targetChannel); } Code Sample 2: public void lock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setString(1, key); ps.setLong(2, System.currentTimeMillis()); ps.setString(3, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to lock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(""); fc.setMultiSelectionEnabled(false); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = 0; boolean save = m_data != null; if (save) option = fc.showSaveDialog(this); else option = fc.showOpenDialog(this); if (option != JFileChooser.APPROVE_OPTION) return; File file = fc.getSelectedFile(); if (file == null) return; log.info(file.toString()); try { if (save) { FileOutputStream os = new FileOutputStream(file); byte[] buffer = (byte[]) m_data; os.write(buffer); os.flush(); os.close(); log.config("Save to " + file + " #" + buffer.length); } else { FileInputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int length = -1; while ((length = is.read(buffer)) != -1) os.write(buffer, 0, length); is.close(); byte[] data = os.toByteArray(); m_data = data; log.config("Load from " + file + " #" + data.length); os.close(); } } catch (Exception ex) { log.log(Level.WARNING, "Save=" + save, ex); } try { fireVetoableChange(m_columnName, null, m_data); } catch (PropertyVetoException pve) { } } Code Sample 2: public Resource get(String serviceUrl, String resourceId, String svcId, boolean appendProfile) throws Exception { Resource resource = new Resource(); String openurl = getURL(serviceUrl, resourceId, svcId, appendProfile); logger.debug("OpenURL Request: " + openurl); URL url; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { InputStream is = huc.getInputStream(); resource.setBytes(IOUtils.getByteArray(is)); resource.setContentType(huc.getContentType()); } else if (code == 404) { return null; } else { logger.error("An error of type " + code + " occurred for " + url.toString()); throw new Exception("Cannot get " + url.toString()); } } catch (MalformedURLException e) { throw new Exception("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new Exception("An IOException occurred attempting to connect to " + openurl); } return resource; }
11
Code Sample 1: public static String EncryptString(String method, String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); if (method.equals("SHA1") || method.equals("MD5")) { try { md = MessageDigest.getInstance(method); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); return null; } } else { return null; } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { String tmp = Integer.toHexString(0xff & byteHash[i]); if (tmp.length() < 2) tmp = "0" + tmp; resultString.append(tmp); } return (resultString.toString()); } Code Sample 2: public static String encrypt(String algorithm, String[] input) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.reset(); for (int i = 0; i < input.length; i++) { if (input[i] != null) md.update(input[i].getBytes("UTF-8")); } byte[] messageDigest = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString((0xf0 & messageDigest[i]) >> 4)); hexString.append(Integer.toHexString(0x0f & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (NullPointerException e) { return new StringBuffer().toString(); } }
00
Code Sample 1: @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); } Code Sample 2: @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int i; String dicomURL = request.getParameter("datasetURL"); String contentType = request.getParameter("contentType"); String studyUID = request.getParameter("studyUID"); String seriesUID = request.getParameter("seriesUID"); String objectUID = request.getParameter("objectUID"); dicomURL += "&contentType=" + contentType + "&studyUID=" + studyUID + "&seriesUID=" + seriesUID + "&objectUID=" + objectUID + "&transferSyntax=1.2.840.10008.1.2.1"; dicomURL = dicomURL.replace("+", "%2B"); InputStream is = null; DataInputStream dis = null; try { URL url = new URL(dicomURL); is = url.openStream(); dis = new DataInputStream(is); for (i = 0; i < dicomData.length; i++) dicomData[i] = dis.readUnsignedByte(); String windowCenter = getElementValue("00281050"); String windowWidth = getElementValue("00281051"); request.getSession(true).setAttribute(WINDOW_CENTER_PARAM, windowCenter == null ? null : windowCenter.trim()); request.getSession(true).setAttribute(WINDOW_WIDTH_PARAM, windowWidth == null ? null : windowWidth.trim()); dis.skipBytes(50000000); is.close(); dis.close(); out.println("Success"); out.close(); } catch (Exception e) { log.error("Unable to read and send the DICOM dataset page", e); } }
00
Code Sample 1: public static byte[] wrapBMP(Image image) throws IOException { if (image.getOriginalType() != Image.ORIGINAL_BMP) throw new IOException("Only BMP can be wrapped in WMF."); InputStream imgIn; byte data[] = null; if (image.getOriginalData() == null) { imgIn = image.url().openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int b = 0; while ((b = imgIn.read()) != -1) out.write(b); imgIn.close(); data = out.toByteArray(); } else data = image.getOriginalData(); int sizeBmpWords = (data.length - 14 + 1) >>> 1; ByteArrayOutputStream os = new ByteArrayOutputStream(); writeWord(os, 1); writeWord(os, 9); writeWord(os, 0x0300); writeDWord(os, 9 + 4 + 5 + 5 + (13 + sizeBmpWords) + 3); writeWord(os, 1); writeDWord(os, 14 + sizeBmpWords); writeWord(os, 0); writeDWord(os, 4); writeWord(os, META_SETMAPMODE); writeWord(os, 8); writeDWord(os, 5); writeWord(os, META_SETWINDOWORG); writeWord(os, 0); writeWord(os, 0); writeDWord(os, 5); writeWord(os, META_SETWINDOWEXT); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeDWord(os, 13 + sizeBmpWords); writeWord(os, META_DIBSTRETCHBLT); writeDWord(os, 0x00cc0020); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); os.write(data, 14, data.length - 14); if ((data.length & 1) == 1) os.write(0); writeDWord(os, 3); writeWord(os, 0); os.close(); return os.toByteArray(); } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
00
Code Sample 1: public void deleteInstance(int instanceId) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, instanceId) == false) throw new ObjectNotFoundException(instanceId); ObjectLinkTable objectLinkList = new ObjectLinkTable(); ObjectAttributeTable objectAttributeList = new ObjectAttributeTable(); objectLinkList.deleteObject(stmt, instanceId); objectAttributeList.deleteObject(stmt, instanceId); stmt.executeUpdate("delete from Objects where ObjectId = " + instanceId); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
11
Code Sample 1: public static void upLoadFile(File sourceFile, File targetFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: private String hashmd5(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; } Code Sample 2: public String calculateProjectMD5(String scenarioName) throws Exception { Scenario s = ScenariosManager.getInstance().getScenario(scenarioName); s.loadParametersAndValues(); String scenarioMD5 = calculateScenarioMD5(s); Map<ProjectComponent, String> map = getProjectMD5(new ProjectComponent[] { ProjectComponent.resources, ProjectComponent.classes, ProjectComponent.suts, ProjectComponent.libs }); map.put(ProjectComponent.currentScenario, scenarioMD5); MessageDigest md = MessageDigest.getInstance("MD5"); Iterator<String> iter = map.values().iterator(); while (iter.hasNext()) { md.update(iter.next().getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
00
Code Sample 1: public static String addWeibo(String weibo, File pic, String uid) throws Throwable { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("_surl", "")); qparams.add(new BasicNameValuePair("_t", "0")); qparams.add(new BasicNameValuePair("location", "home")); qparams.add(new BasicNameValuePair("module", "stissue")); if (pic != null) { String picId = upLoadImg(pic, uid); qparams.add(new BasicNameValuePair("pic_id", picId)); } qparams.add(new BasicNameValuePair("rank", "weibo")); qparams.add(new BasicNameValuePair("text", weibo)); HttpPost post = getHttpPost("http://weibo.com/aj/mblog/add?__rnd=1333611402611", uid); UrlEncodedFormEntity params = new UrlEncodedFormEntity(qparams, HTTP.UTF_8); post.setEntity(params); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity, HTTP.UTF_8); post.abort(); return content; } 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 String getHtmlSource(String url) { StringBuffer codeBuffer = null; BufferedReader in = null; URLConnection uc = null; try { uc = new URL(url).openConnection(); uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8")); codeBuffer = new StringBuffer(); String tempCode = ""; while ((tempCode = in.readLine()) != null) { codeBuffer.append(tempCode).append("\n"); } in.close(); tempCode = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != in) in = null; if (null != uc) uc = null; } return codeBuffer.toString(); } Code Sample 2: private void _readValuesFromNetwork() { if (_intrinsicValuesByAttribute == null) { NSMutableDictionary<String, Object> values = new NSMutableDictionary<String, Object>(3); values.setObjectForKey(Boolean.FALSE, "NetworkFailure"); try { URLConnection connection = url().openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpconnect = (HttpURLConnection) connection; httpconnect.setRequestMethod("HEAD"); switch(httpconnect.getResponseCode()) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_NOT_MODIFIED: values.setObjectForKey(Boolean.TRUE, MD.FSExists); break; default: values.setObjectForKey(Boolean.FALSE, MD.FSExists); } LOG.info("_readValuesFromNetwork: " + httpconnect.toString()); values.setObjectForKey(new NSTimestamp(httpconnect.getLastModified()), MD.FSContentChangeDate); values.setObjectForKey(new Integer(httpconnect.getContentLength()), MD.FSSize); } else { values.setObjectForKey(Boolean.FALSE, MD.FSExists); } } catch (Exception x) { values.setObjectForKey(Boolean.FALSE, MD.FSExists); values.setObjectForKey(Boolean.TRUE, "NetworkFailure"); } _intrinsicValuesByAttribute = values; } }
00
Code Sample 1: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream inputStream = url.openStream(); try { return getAudioInputStream(inputStream); } catch (UnsupportedAudioFileException e) { inputStream.close(); throw e; } catch (IOException e) { inputStream.close(); throw e; } } Code Sample 2: public static void BubbleSortInt2(int[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { int temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; }
00
Code Sample 1: public int deleteRecord(Publisher publisher, MmdQueryCriteria criteria) throws Exception { int nRows = 0; if (!publisher.getIsAdministrator()) { throw new ImsServiceException("DeleteRecordsRequest: not authorized."); } PreparedStatement st = null; ManagedConnection mc = returnConnection(); Connection con = mc.getJdbcConnection(); DatabaseMetaData dmt = con.getMetaData(); String database = dmt.getDatabaseProductName().toLowerCase(); boolean autoCommit = con.getAutoCommit(); con.setAutoCommit(false); try { StringBuilder sbWhere = new StringBuilder(); Map<String, Object> args = criteria.appendWherePhrase(null, sbWhere, publisher); StringBuilder sbData = new StringBuilder(); if (database.contains("mysql")) { sbData.append(" DELETE ").append(getResourceDataTableName()).append(" FROM ").append(getResourceDataTableName()); sbData.append(" LEFT JOIN ").append(getResourceTableName()); sbData.append(" ON ").append(getResourceDataTableName()).append(".ID=").append(getResourceTableName()).append(".ID WHERE ").append(getResourceTableName()).append(".ID in ("); sbData.append(" SELECT ID FROM ").append(getResourceTableName()).append(" "); if (sbWhere.length() > 0) { sbData.append(" WHERE ").append(sbWhere.toString()); } sbData.append(")"); } else { sbData.append(" DELETE FROM ").append(getResourceDataTableName()); sbData.append(" WHERE ").append(getResourceDataTableName()).append(".ID in ("); sbData.append(" SELECT ID FROM ").append(getResourceTableName()).append(" "); if (sbWhere.length() > 0) { sbData.append(" WHERE ").append(sbWhere.toString()); } sbData.append(")"); } st = con.prepareStatement(sbData.toString()); criteria.applyArgs(st, 1, args); logExpression(sbData.toString()); st.executeUpdate(); StringBuilder sbSql = new StringBuilder(); sbSql.append("DELETE FROM ").append(getResourceTableName()).append(" "); if (sbWhere.length() > 0) { sbSql.append(" WHERE ").append(sbWhere.toString()); } closeStatement(st); st = con.prepareStatement(sbSql.toString()); criteria.applyArgs(st, 1, args); logExpression(sbSql.toString()); nRows = st.executeUpdate(); con.commit(); } catch (Exception ex) { con.rollback(); throw ex; } finally { closeStatement(st); con.setAutoCommit(autoCommit); } return nRows; } Code Sample 2: public static boolean copyFile(String fromfile, String tofile) { File from = new File(fromfile); File to = new File(tofile); if (!from.exists()) return false; if (to.exists()) { log.error(tofile + "exists already"); return false; } BufferedInputStream in = null; BufferedOutputStream out = null; FileInputStream fis = null; FileOutputStream ois = null; boolean flag = true; try { to.createNewFile(); fis = new FileInputStream(from); ois = new FileOutputStream(to); in = new BufferedInputStream(fis); out = new BufferedOutputStream(ois); byte[] buf = new byte[2048]; int readBytes = 0; while ((readBytes = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, readBytes); } } catch (IOException e) { log.error(e); flag = false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log.error(e); flag = false; } } return flag; }
00
Code Sample 1: private String send(String method, String contentType, String urlStr, String body) throws MalformedURLException, IOException { HttpURLConnection postCon = (HttpURLConnection) new URL(getUrl(urlStr)).openConnection(); postCon.setRequestMethod(method); postCon.setDoOutput(true); postCon.setDoInput(true); if (cookie != null) { postCon.setRequestProperty("Cookie", cookie); if (contentType != null) { postCon.setRequestProperty("Content-type", contentType); } postCon.setRequestProperty("Content-Length", body == null ? "0" : Integer.toString(body.length())); } if (body != null) { OutputStream os = postCon.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os); out.write(body); out.close(); } InputStream is = null; try { is = postCon.getInputStream(); } catch (IOException ioe) { is = postCon.getErrorStream(); } int resCode = postCon.getResponseCode(); if (resCode == 201 || resCode == 202) { String loc = postCon.getHeaderField("Location"); System.out.println("loc:" + loc); return loc; } StringBuffer sb = StreamUtil.readStream(is); return sb.toString(); } Code Sample 2: public static void call(String host, String port, String method, String[] params) { cat.debug("call (host:" + host + " port:" + port + " method:" + method); try { String message = null; StringBuffer bufMessage = new StringBuffer(); bufMessage.append("<?xml version='1.0' encoding='ISO-8859-1'?>"); bufMessage.append("<methodCall>"); bufMessage.append("<methodName>"); bufMessage.append(method); bufMessage.append("</methodName>"); bufMessage.append("<params>"); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { bufMessage.append("<param><value><![CDATA[" + params[i] + "]]></value></param>"); } } bufMessage.append("</params></methodCall>"); message = bufMessage.toString(); bufMessage = null; String stringUrl = "http://" + host + ":" + port + "/RPC2"; cat.debug("Sending message to: " + stringUrl + "\n" + message); URL url = new URL(stringUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); urlConnection.getOutputStream().write(message.getBytes()); urlConnection.getOutputStream().flush(); urlConnection.getOutputStream().close(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { cat.debug("#server# " + line); } bufferedReader.close(); } catch (Exception e) { cat.debug("Unable to send link to Gnowsis!", e); } }
00
Code Sample 1: @Action(value = "ajaxFileUploads", results = { }) public void ajaxFileUploads() throws IOException { String extName = ""; String newFilename = ""; String nowTimeStr = ""; String realpath = ""; if (Validate.StrNotNull(this.getImgdirpath())) { realpath = "Uploads/" + this.getImgdirpath() + "/"; } else { realpath = this.isexistdir(); } SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath(""); savePath = savePath + realpath; HttpServletResponse response = ServletActionContext.getResponse(); int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000; sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); nowTimeStr = sDateFormat.format(new Date()); String filename = request.getHeader("X-File-Name"); if (filename.lastIndexOf(".") >= 0) { extName = filename.substring(filename.lastIndexOf(".")); } newFilename = nowTimeStr + rannum + extName; PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage()); } try { is = request.getInputStream(); fos = new FileOutputStream(new File(savePath + newFilename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success:'" + realpath + newFilename + "'}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { this.setImgdirpath(null); fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: private void addEMInformation() { try { long emDate = System.currentTimeMillis(); if (_local == true) { File emFile = new File("emprotz.dat"); if (!emFile.exists()) { return; } emDate = emFile.lastModified(); } if (emDate > this._emFileDate) { this._emFileDate = emDate; this._emDate = emDate; for (int ii = 0; ii < this._projectInfo.size(); ii++) { Information info = getInfo(ii); if (info != null) { info._emDeadline = null; info._emFrames = null; info._emValue = null; } } Reader reader = null; if (_local == true) { reader = new FileReader("emprotz.dat"); } else { StringBuffer urlName = new StringBuffer(); urlName.append("http://home.comcast.net/"); urlName.append("~wxdude1/emsite/download/"); urlName.append("emprotz.zip"); try { URL url = new URL(urlName.toString()); InputStream stream = url.openStream(); ZipInputStream zip = new ZipInputStream(stream); zip.getNextEntry(); reader = new InputStreamReader(zip); } catch (MalformedURLException mue) { mue.printStackTrace(); } } BufferedReader file = new BufferedReader(reader); try { String line1 = null; int count = 0; while ((line1 = file.readLine()) != null) { String line2 = (line1 != null) ? file.readLine() : null; String line3 = (line2 != null) ? file.readLine() : null; String line4 = (line3 != null) ? file.readLine() : null; count++; if ((count > 1) && (line1 != null) && (line2 != null) && (line3 != null) && (line4 != null)) { if (line1.length() > 2) { int posBegin = line1.indexOf("\"", 0); int posEnd = line1.indexOf("\"", posBegin + 1); if ((posBegin >= 0) && (posEnd >= 0)) { String project = line1.substring(posBegin + 1, posEnd - posBegin); int projectNum = Integer.parseInt(project); Integer deadline = Integer.valueOf(line2.trim()); Double value = Double.valueOf(line3.trim()); Integer frames = Integer.valueOf(line4.trim()); Information info = getInfo(projectNum); if (info == null) { info = createInfo(projectNum); } if (info._emValue == null) { info._emDeadline = deadline; info._emFrames = frames; info._emValue = value; } } } } } } catch (Exception e) { e.printStackTrace(); } finally { file.close(); } } } catch (FileNotFoundException e) { } catch (IOException e) { } }
00
Code Sample 1: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } } Code Sample 2: public File getURL(URL url) throws IOException { URLConnection conn = null; File tempFile = null; Logger l = Logger.instance(); String className = getClass().getName(); l.log(Logger.DEBUG, loggerPrefix, className + ".getURL", "GET URL " + url.toString()); try { conn = url.openConnection(); tempFile = readIntoTempFile(conn.getInputStream()); } catch (IOException ioe) { l.log(Logger.ERROR, loggerPrefix, className + ".getURL", ioe); throw ioe; } finally { conn = null; } l.log(Logger.DEBUG, loggerPrefix, className + ".getURL", "received URL"); return tempFile; }
00
Code Sample 1: 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; } Code Sample 2: 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; }
00
Code Sample 1: private File prepareFileForUpload(File source, String s3key) throws IOException { File tmp = File.createTempFile("dirsync", ".tmp"); tmp.deleteOnExit(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new DeflaterOutputStream(new CryptOutputStream(new FileOutputStream(tmp), cipher, getDataEncryptionKey())); IOUtils.copy(in, out); in.close(); out.close(); return tmp; } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } Code Sample 2: public HttpURLConnection connect() throws IOException { if (url == null) { return null; } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (previousETag != null) { connection.addRequestProperty("If-None-Match", previousETag); } if (previousLastModified != null) { connection.addRequestProperty("If-Modified-Since", previousLastModified); } return connection; }
11
Code Sample 1: public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::执行SQL语句操作(更新数据 有参数):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::执行SQL语句操作(更新数据 无参数):" + strSql + "失败! 参数设置类型错误!"); con.rollback(); throw ex; } return flag; } Code Sample 2: public static boolean insereMidia(final Connection con, Midia mid, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodMidia(con, mid); GeraID.gerarCodDescricao(con, desc); String titulo = mid.getTitulo().replaceAll("['\"]", ""); String coment = mid.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO midia VALUES(" + mid.getCodigo() + ", '" + titulo + "', '" + coment + "','" + mid.getUrl() + "', '" + mid.getTipo() + "', " + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO mid_aut VALUES(" + mid.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "MIDIA: Database error", JOptionPane.ERROR_MESSAGE); System.err.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getMessage()); } } }
00
Code Sample 1: public ReqJsonContent(String useragent, String urlstr, String domain, String pathinfo, String alarmMessage) throws IOException { URL url = new URL(urlstr); URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", useragent); conn.setRequestProperty("pathinfo", pathinfo); conn.setRequestProperty("domain", domain); try { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF8")); response = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); jsonContectResult = response.toString(); } catch (SocketTimeoutException e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } catch (Exception e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } } Code Sample 2: public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.exit(-1); } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); }
11
Code Sample 1: public boolean check(String credentials) throws IOException { if (credentials == null) return true; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); md.update(credentials.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(MessageDigester.byteArrayToHex(ha2).getBytes("ISO-8859-1")); byte[] digest = md.digest(); return (MessageDigester.byteArrayToHex(digest).equalsIgnoreCase(response)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 not supported"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding not supported"); } } Code Sample 2: PasswordTableWindow(String login) { super(login + ", tecle a senha de uso �nico"); this.login = login; Error.log(4001, "Autentica��o etapa 3 iniciada."); Container container = getContentPane(); container.setLayout(new FlowLayout()); btnNumber = new JButton[10]; btnOK = new JButton("OK"); btnClear = new JButton("Limpar"); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 10)); ResultSet rs; Statement stmt; String sql; Vector<Integer> result = new Vector<Integer>(); sql = "select key from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result.add(rs.getInt("key")); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r = rn.nextInt(); if (result.size() == 0) { rn = new Random(); Vector<Integer> passwordVector = new Vector<Integer>(); Vector<String> hashVector = new Vector<String>(); for (int i = 0; i < 10; i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < 10; i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < 10; i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "nova tabela de senhas criada para o usu�rio " + login + "."); Error.log(1002, "Sistema encerrado"); System.exit(0); } if (r < 0) r = r * (-1); int index = r % result.size(); if (index > result.size()) index = 0; key = result.get(index); labelKey = new JLabel("Chave n�mero " + key + " "); passwordField = new JPasswordField(12); ButtonHandler handler = new ButtonHandler(); for (int i = 0; i < 10; i++) { btnNumber[i] = new JButton("" + i); buttonPanel.add(btnNumber[i]); btnNumber[i].addActionListener(handler); } btnOK.addActionListener(handler); btnClear.addActionListener(handler); container.add(buttonPanel); container.add(passwordField); container.add(labelKey); container.add(btnOK); container.add(btnClear); setSize(325, 200); setVisible(true); }
00
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 RandomGUID() { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage()); } try { long time = System.currentTimeMillis(); long rand = 0; rand = myRand.nextLong(); StringBuffer sb = new StringBuffer(); sb.append(s_id); sb.append(":"); sb.append(Long.toString(time)); sb.append(":"); sb.append(Long.toString(rand)); md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); sb.setLength(0); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage()); } }
00
Code Sample 1: public static void registerProviders(ResteasyProviderFactory factory) throws Exception { Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName()); LinkedHashSet<String> set = new LinkedHashSet<String>(); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStream is = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.equals("")) continue; set.add(line); } } finally { is.close(); } } for (String line : set) { try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(line); factory.registerProvider(clazz, true); } catch (NoClassDefFoundError e) { logger.warn("NoClassDefFoundError: Unable to load builtin provider: " + line); } catch (ClassNotFoundException e) { logger.warn("ClassNotFoundException: Unable to load builtin provider: " + line); } } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: public static String getDigestResponse(String user, String password, String method, String requri, String authstr) { String realm = ""; String nonce = ""; String opaque = ""; String algorithm = ""; String qop = ""; StringBuffer digest = new StringBuffer(); String cnonce; String noncecount; String pAuthStr = authstr; int ptr = 0; String response = ""; int i = 0; StringTokenizer st = new StringTokenizer(pAuthStr, ","); StringTokenizer stprob = null; String str = null; String key = null; String value = null; Properties probs = new Properties(); while (st.hasMoreTokens()) { String nextToken = st.nextToken(); stprob = new StringTokenizer(nextToken, "="); key = stprob.nextToken(); value = stprob.nextToken(); if (value.charAt(0) == '"' || value.charAt(0) == '\'') { value = value.substring(1, value.length() - 1); } probs.put(key, value); } digest.append("Digest username=\"" + user + "\", "); digest.append("realm=\""); digest.append(probs.getProperty("realm")); digest.append("\", "); digest.append("nonce=\""); digest.append(probs.getProperty("nonce")); digest.append("\", "); digest.append("uri=\"" + requri + "\", "); cnonce = "abcdefghi"; noncecount = "00000001"; String toDigest = user + ":" + realm + ":" + password; byte[] digestbuffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toDigest.getBytes()); digestbuffer = md.digest(); } catch (Exception e) { System.err.println("Error creating digest request: " + e); return null; } digest.append("qop=\"auth\", "); digest.append("cnonce=\"" + cnonce + "\", "); digest.append("nc=" + noncecount + ", "); digest.append("response=\"" + response + "\""); if (probs.getProperty("opaque") != null) { digest.append(", opaque=\"" + probs.getProperty("opaque") + "\""); } System.out.println("SipProtocol: Digest calculated."); return digest.toString(); } Code Sample 2: 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)); } } } }
11
Code Sample 1: @Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; } Code Sample 2: @Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { if (doc instanceof XMLDOMDocument) { writer.writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { ManagedFile result = resolveFileFor(folder, (BinaryDocument) doc); IOUtils.copy(bin.getContent().getInputStream(), result.getContent().getOutputStream()); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
00
Code Sample 1: public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { throw new RuntimeException("Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("NoSuchAlgorithmException : " + e.getMessage()); } return digest; } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(sourceFile); os = new FileOutputStream(destFile); IOUtils.copy(is, os); } finally { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.debug("Random GUID error: " + e.getMessage()); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static void main(String[] args) throws Exception { String urlString = "http://php.tech.sina.com.cn/download/d_load.php?d_id=7877&down_id=151542"; urlString = EncodeUtils.encodeURL(urlString); URL url = new URL(urlString); System.out.println("第一次:" + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); Map req = conn.getRequestProperties(); System.out.println("第一次请求头:"); printMap(req); conn.connect(); System.out.println("第一次响应:"); System.out.println(conn.getResponseMessage()); int code = conn.getResponseCode(); System.out.println("第一次code:" + code); printMap(conn.getHeaderFields()); System.out.println(conn.getURL().getFile()); if (code == 404 && !(conn.getURL() + "").equals(urlString)) { System.out.println(conn.getURL()); String tmp = URLEncoder.encode(conn.getURL().toString(), "gbk"); System.out.println(URLEncoder.encode("在线音乐播放脚本", "GBK")); System.out.println(tmp); url = new URL(tmp); System.out.println("第二次:" + url); conn = (HttpURLConnection) url.openConnection(); System.out.println("第二次响应:"); System.out.println("code:" + code); printMap(conn.getHeaderFields()); } }
00
Code Sample 1: private void pushResource(String peerId, String communityId, String resourceFilePath, List<String> attachmentFilePaths) throws IOException { String urlString = "http://" + peerId + "/upload"; HttpURLConnection uploadConnection = null; DataOutputStream connOutput = null; FileInputStream fileInput = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "232404jkg4220957934FW"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { File resourceFile = new File(resourceFilePath); if (!resourceFile.exists()) { LOG.error("JTellaAdapter: Resource file could not be found for push: " + resourceFilePath); return; } List<File> attachments = new ArrayList<File>(); for (String attachmentPath : attachmentFilePaths) { File attachFile = new File(attachmentPath); if (!attachFile.exists()) { LOG.error("JTellaAdapter: Attachment file could not be found for push: " + attachmentPath); return; } attachments.add(attachFile); } LOG.debug("JTellaAdapter: Initiating push to: " + urlString); URL url = new URL(urlString); uploadConnection = (HttpURLConnection) url.openConnection(); uploadConnection.setDoInput(true); uploadConnection.setDoOutput(true); uploadConnection.setUseCaches(false); uploadConnection.setRequestMethod("POST"); uploadConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); uploadConnection.setRequestProperty("Connection", "Keep-Alive"); uploadConnection.setRequestProperty("User-Agent", "UP2P"); uploadConnection.setRequestProperty("Accept", "[star]/[star]"); connOutput = new DataOutputStream(uploadConnection.getOutputStream()); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:community\"" + lineEnd + lineEnd); connOutput.writeBytes(communityId + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:pushupload\"" + lineEnd + lineEnd + "true" + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); boolean fileWriteComplete = false; boolean resourceFileWritten = false; File nextFile = null; while (!fileWriteComplete) { if (!resourceFileWritten) { nextFile = resourceFile; } else { nextFile = attachments.remove(0); } LOG.debug("JTellaAdapter: PUSHing file: " + nextFile.getAbsolutePath()); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:filename\";" + " filename=\"" + nextFile.getName() + "\"" + lineEnd); connOutput.writeBytes(lineEnd); fileInput = new FileInputStream(nextFile); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInput.read(buffer, 0, bufferSize); while (bytesRead > 0) { connOutput.write(buffer, 0, bufferSize); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInput.read(buffer, 0, bufferSize); } connOutput.writeBytes(lineEnd); if (attachments.isEmpty()) { connOutput.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); } else { connOutput.writeBytes(twoHyphens + boundary + lineEnd); } resourceFileWritten = true; if (attachments.isEmpty()) { fileWriteComplete = true; } } BufferedReader inStream = new BufferedReader(new InputStreamReader(uploadConnection.getInputStream())); while (inStream.readLine() != null) ; inStream.close(); LOG.debug("JTellaAdapter: Push upload was succesful."); } catch (MalformedURLException ex) { LOG.error("JTellaAdapter: pushResource Malformed URL: " + ex); throw new IOException("pushResource failed for URL: " + urlString); } catch (IOException ioe) { LOG.error("JTellaAdapter: pushResource IOException: " + ioe); throw new IOException("pushResource failed for URL: " + urlString); } finally { try { if (fileInput != null) { fileInput.close(); } if (connOutput != null) { connOutput.flush(); } if (connOutput != null) { connOutput.close(); } if (uploadConnection != null) { uploadConnection.disconnect(); } } catch (IOException e) { LOG.error("JTellaAdapter: pushResource failed to close connection streams."); } } } Code Sample 2: public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); Iterator<LDAPModification> it = mods.iterator(); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); int id = this.getId(dn, con); while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() == LDAPModification.REPLACE) { String attributeName = mod.getAttribute().getName(); if (attributeName.equals(db2ldap.get("first")) || attributeName.equals(db2ldap.get("last"))) { PreparedStatement ps = con.prepareStatement("UPDATE USERS SET " + (attributeName.equals(db2ldap.get("first")) ? "first" : "last") + "=? WHERE username=?"); ps.setString(1, mod.getAttribute().getStringValue()); ps.setString(2, uid); ps.executeUpdate(); ps.close(); } else if (attributeName.equals(db2ldap.get("username"))) { throw new LDAPException("Can not modify the rdn", LDAPException.NOT_ALLOWED_ON_RDN, "Can not perform modify"); } else if (attributeName.equals(db2ldap.get("name"))) { PreparedStatement ps = con.prepareStatement("DELETE FROM locationmap WHERE person=?"); ps.setInt(1, id); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("INSERT INTO locationmap (person,location) VALUES (?,?)"); PreparedStatement pssel = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); String[] vals = mod.getAttribute().getStringValueArray(); for (int i = 0; i < vals.length; i++) { pssel.setString(1, vals[i]); ResultSet rs = pssel.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } int lid = rs.getInt("id"); ps.setInt(1, id); ps.setInt(2, lid); ps.executeUpdate(); } ps.close(); pssel.close(); } } else if (mod.getOp() == LDAPModification.DELETE) { if (mod.getAttribute().getName().equals(db2ldap.get("name"))) { String[] vals = mod.getAttribute().getStringValueArray(); if (vals.length == 0) { PreparedStatement ps = con.prepareStatement("DELETE FROM locationmap WHERE person=?"); ps.setInt(1, id); ps.executeUpdate(); ps.close(); } else { PreparedStatement ps = con.prepareStatement("DELETE FROM locationmap WHERE person=? and location=?"); PreparedStatement pssel = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); for (int i = 0; i < vals.length; i++) { pssel.setString(1, vals[i]); ResultSet rs = pssel.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } int lid = rs.getInt("id"); ps.setInt(1, id); ps.setInt(2, lid); ps.executeUpdate(); } ps.close(); pssel.close(); } } else { throw new LDAPException("Can not delete attribute " + mod.getAttribute().getName(), LDAPException.INVALID_ATTRIBUTE_SYNTAX, ""); } } else if (mod.getOp() == LDAPModification.ADD) { if (mod.getAttribute().getName().equals(db2ldap.get("name"))) { String[] vals = mod.getAttribute().getStringValueArray(); PreparedStatement ps = con.prepareStatement("INSERT INTO locationmap (person,location) VALUES (?,?)"); PreparedStatement pssel = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); for (int i = 0; i < vals.length; i++) { pssel.setString(1, vals[i]); ResultSet rs = pssel.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } int lid = rs.getInt("id"); ps.setInt(1, id); ps.setInt(2, lid); ps.executeUpdate(); } ps.close(); pssel.close(); } else { throw new LDAPException("Can not delete attribute " + mod.getAttribute().getName(), LDAPException.INVALID_ATTRIBUTE_SYNTAX, ""); } } } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
11
Code Sample 1: public static void DecodeMapFile(String mapFile, String outputFile) throws Exception { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; InputStream map; OutputStream output; try { map = new FileInputStream(mapFile); } catch (Exception e) { throw new Exception("Map file error", e); } try { output = new FileOutputStream(outputFile); } catch (Exception e) { throw new Exception("Map file error", e); } while ((nread = map.read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.write(buffer, 0, nread); } map.close(); output.close(); } Code Sample 2: protected InputStream createIconType(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { JavaliController.debug(JavaliController.LG_VERBOSE, "Creating iconType"); String cHash = PRM_TYPE + "=" + TP_ICON; String iconName = req.getParameter("iconName"); if (iconName == null) { res.sendError(res.SC_NOT_FOUND); return null; } Locale loc = null; HttpSession sess = req.getSession(false); JavaliSession jsess = null; int menuType = -1; String menuTypeString = req.getParameter(PRM_MENU_TYPE); try { menuType = new Integer(menuTypeString).intValue(); } catch (Exception e) { } if (sess != null) jsess = (JavaliSession) sess.getAttribute(FormConstants.SESSION_BINDING); if (jsess != null && jsess.getUser() != null) loc = jsess.getUser().getLocale(); else if (sess != null) loc = (Locale) sess.getAttribute(FormConstants.LOCALE_BINDING); if (loc == null) loc = Locale.getDefault(); if (menuType == -1) menuType = MENU_TYPE_TEXTICON; String iconText = JavaliResource.getString("icon." + iconName, loc); if (iconText == null) { iconText = req.getParameter(PRM_MENU_NAME); if (iconText == null) iconText = ""; } cHash += ", " + PRM_ICON_NAME + "=" + iconName + ", text=" + iconText + ", menuType=" + menuType; String iconFileName = null; String fontName = req.getParameter(PRM_FONT_NAME); if (fontName == null) { fontName = "Helvetica"; } cHash += "," + PRM_FONT_NAME + "=" + fontName; String fontSizeString = req.getParameter(PRM_FONT_SIZE); int fontSize; try { fontSize = Integer.parseInt(fontSizeString); } catch (NumberFormatException nfe) { fontSize = 12; } cHash += "," + PRM_FONT_SIZE + "=" + fontSize; String fontTypeString = req.getParameter(PRM_FONT_TYPE); int fontType = Font.BOLD; if ("PLAIN".equalsIgnoreCase(fontTypeString)) fontType = Font.PLAIN; if ("BOLD".equalsIgnoreCase(fontTypeString)) fontType = Font.BOLD; if ("ITALIC".equalsIgnoreCase(fontTypeString)) fontType = Font.ITALIC; if ("ITALICBOLD".equalsIgnoreCase(fontTypeString) || "BOLDITALIC".equalsIgnoreCase(fontTypeString) || "BOLD_ITALIC".equalsIgnoreCase(fontTypeString) || "ITALIC_BOLD".equalsIgnoreCase(fontTypeString)) { fontType = Font.ITALIC | Font.BOLD; } cHash += "," + PRM_FONT_TYPE + "=" + fontType; String fontColor = req.getParameter(PRM_FONT_COLOR); if (fontColor == null || fontColor.equals("")) fontColor = "0x000000"; cHash += "," + PRM_FONT_COLOR + "=" + fontColor; String fName = cacheInfo.file(cHash); JavaliController.debug(JavaliController.LG_VERBOSE, "Called for: " + fName); if (fName == null) { JavaliController.debug(JavaliController.LG_VERBOSE, "No cache found for: " + cHash); if (getServletConfig() != null && getServletConfig().getServletContext() != null) { if (iconName != null && iconName.startsWith("/")) iconFileName = getServletConfig().getServletContext().getRealPath(iconName + ".gif"); else iconFileName = getServletConfig().getServletContext().getRealPath("/icons/" + iconName + ".gif"); File iconFile = new File(iconFileName); if (!iconFile.exists()) { JavaliController.debug(JavaliController.LG_VERBOSE, "Could not find: " + iconFileName); res.sendError(res.SC_NOT_FOUND); return null; } iconFileName = iconFile.getAbsolutePath(); JavaliController.debug(JavaliController.LG_VERBOSE, "file: " + iconFileName + " and cHash=" + cHash); } else { JavaliController.debug(JavaliController.LG_VERBOSE, "No ServletConfig=" + getServletConfig() + " or servletContext"); res.sendError(res.SC_NOT_FOUND); return null; } File tmp = File.createTempFile(PREFIX, SUFIX, cacheDir); OutputStream out = new FileOutputStream(tmp); if (menuType == MENU_TYPE_ICON) { FileInputStream in = new FileInputStream(iconFileName); byte buf[] = new byte[2048]; int read = -1; while ((read = in.read(buf)) != -1) out.write(buf, 0, read); } else if (menuType == MENU_TYPE_TEXT) MessageImage.sendAsGIF(MessageImage.makeMessageImage(iconText, fontName, fontSize, fontType, fontColor, false, "0x000000", true), out); else MessageImage.sendAsGIF(MessageImage.makeIconImage(iconFileName, iconText, fontName, fontColor, fontSize, fontType), out); out.close(); cacheInfo.putFile(cHash, tmp); fName = cacheInfo.file(cHash); } return new FileInputStream(new File(cacheDir, fName)); }
00
Code Sample 1: protected void updateJava2ScriptProject(String prjFolder, String binRelative) { try { File cpFile = new File(prjFolder, ".classpath"); FileInputStream fis = new FileInputStream(cpFile); String classpath = J2SLaunchingUtil.readAFile(fis); if (classpath != null) { boolean needUpdate = false; if (classpath.indexOf("ECLIPSE_SWT") == -1 && classpath.indexOf("SWT_LIBRARY") == -1 && classpath.indexOf("eclipse.swt") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry kind=\"var\" path=\"ECLIPSE_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_SWT") == -1 && classpath.indexOf("ajaxswt.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_SWT_SRC\" kind=\"var\" path=\"AJAX_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_RPC") == -1 && classpath.indexOf("ajaxrpc.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_RPC_SRC\" kind=\"var\" path=\"AJAX_RPC\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_PIPE") == -1 && classpath.indexOf("ajaxpipe.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_PIPE_SRC\" kind=\"var\" path=\"AJAX_PIPE\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (needUpdate) { try { FileOutputStream fos = new FileOutputStream(cpFile); fos.write(classpath.getBytes("utf-8")); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } File webinf = new File(prjFolder, "WEB-INF"); webinf.mkdir(); new File(webinf, "classes").mkdir(); File lib = new File(webinf, "lib"); lib.mkdir(); IPath newPath = null; URL starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); String root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxrpc.jar"); File rpcFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(rpcFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxrpc.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxpipe.jar"); File pipeFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(pipeFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxpipe.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } StringBuffer buildxml = new StringBuffer(); buildxml.append("<?xml version=\"1.0\"?>\r\n"); buildxml.append("<project name=\"java2script.servlet.pack\" default=\"pack.war\" basedir=\".\">\r\n"); buildxml.append(" <description>Pack Java2Script Servlet Application</description>\r\n"); buildxml.append("\r\n"); String name = new File(prjFolder).getName(); buildxml.append(" <property name=\"java2script.app.name\" value=\"" + name + "\"/>\r\n"); buildxml.append(" <property name=\"bin.folder\" value=\"${basedir}/../" + binRelative + "\"/>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.war\" depends=\"pack.jar\">\r\n"); buildxml.append(" <tstamp>\r\n"); buildxml.append(" <format property=\"now\" pattern=\"yyyy-MM-dd-HH-mm-ss\"/>\r\n"); buildxml.append(" </tstamp>\r\n"); buildxml.append(" <delete file=\"${basedir}/../${java2script.app.name}.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../${java2script.app.name}.${now}.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/../\">\r\n"); buildxml.append(" <exclude name=\"src/**\"/>\r\n"); buildxml.append(" <exclude name=\"META-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.java\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.class\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" <fileset dir=\"${basedir}/..\">\r\n"); buildxml.append(" <include name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/build.xml\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" <copy file=\"${basedir}/../${java2script.app.name}.${now}.war\"\r\n"); buildxml.append(" tofile=\"${basedir}/../${java2script.app.name}.war\"/>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.jar\">\r\n"); buildxml.append(" <delete file=\"${basedir}/lib/${java2script.app.name}.jar\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/lib/${java2script.app.name}.jar\">\r\n"); buildxml.append(" <fileset dir=\"${bin.folder}\">\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.html\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.js\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.css\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.bmp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.gif\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.png\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpeg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root); String ajaxPath = newPath.toOSString(); String key = "net.sf.j2s.ajax"; int idx = ajaxPath.lastIndexOf(key); if (idx != -1) { ajaxPath = ajaxPath.substring(0, idx) + "net.sf.j2s.lib" + ajaxPath.substring(idx + key.length()); } File libFile = new File(ajaxPath); String j2sRelativePath = FileUtil.toRelativePath(libFile.getAbsolutePath(), webinf.getAbsolutePath()); if (j2sRelativePath.length() > 0 && !j2sRelativePath.endsWith("/")) { j2sRelativePath += "/"; } int slashIndex = j2sRelativePath.lastIndexOf('/', j2sRelativePath.length() - 2); String pluginPath = j2sRelativePath.substring(0, slashIndex); String libPluginPath = j2sRelativePath.substring(slashIndex + 1, j2sRelativePath.length() - 1); buildxml.append(" <target name=\"pack.plugins.j2slib.war\">\r\n"); buildxml.append(" <delete file=\"${basedir}/../plugins.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../plugins.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/" + pluginPath + "/\">\r\n"); buildxml.append(" <include name=\"" + libPluginPath + "/**\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/library.jar\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/META-INF/**\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append("</project>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "build.xml")); fos.write(buildxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } StringBuffer webxml = new StringBuffer(); webxml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"); webxml.append("<!DOCTYPE web-app\r\n"); webxml.append(" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\r\n"); webxml.append(" \"http://java.sun.com/dtd/web-app_2_3.dtd\">\r\n"); webxml.append("<web-app>\r\n"); webxml.append(" <display-name>Java2Script</display-name>\r\n"); webxml.append(" <description>Java2Script application</description>\r\n"); webxml.append(genereateServlet("simplerpc", "net.sf.j2s.ajax.SimpleRPCHttpServlet")); webxml.append(genereateServlet("piperpc", "net.sf.j2s.ajax.CompoundPipeRPCHttpServlet")); webxml.append(" <servlet>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <servlet-class>net.sf.j2s.ajax.SimplePipeHttpServlet</servlet-class>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.query.timeout</param-name>\r\n"); webxml.append(" <param-value>20000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.script.breakout</param-name>\r\n"); webxml.append(" <param-value>1200000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.max.items.per.query</param-name>\r\n"); webxml.append(" <param-value>60</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" </servlet>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplerpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplerpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>piperpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/piperpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplepipe</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append("</web-app>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "web.xml")); fos.write(webxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } } Code Sample 2: public void testSavepoint4() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #savepoint4 (data int)"); stmt.close(); con.setAutoCommit(false); for (int i = 0; i < 3; i++) { System.out.println("iteration: " + i); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)"); pstmt.setInt(1, 1); assertTrue(pstmt.executeUpdate() == 1); Savepoint savepoint = con.setSavepoint(); assertNotNull(savepoint); assertTrue(savepoint.getSavepointId() == 1); try { savepoint.getSavepointName(); assertTrue(false); } catch (SQLException e) { } pstmt.setInt(1, 2); assertTrue(pstmt.executeUpdate() == 1); pstmt.close(); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(savepoint); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(); } con.setAutoCommit(true); }
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 TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
00
Code Sample 1: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } Code Sample 2: public static String getMd5Digest(String pInput) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(pInput.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032x", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
00
Code Sample 1: private void fetchAvailable(ProgressObserver po) { if (po == null) throw new IllegalArgumentException("the progress observer can't be null"); if (availables == null) availables = new ArrayList<Dictionary>(); else availables.clear(); if (installed == null) initInstalled(); File home = SpellCheckPlugin.getHomeDir(jEdit.getActiveView()); File target = new File(home, "available.lst"); try { boolean skipDownload = false; if (target.exists()) { long modifiedDate = target.lastModified(); Calendar c = Calendar.getInstance(); c.setTimeInMillis(modifiedDate); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.HOUR, -1); skipDownload = yesterday.before(c); } String enc = null; if (!skipDownload) { URL available_url = new URL(jEdit.getProperty(OOO_DICTS_PROP) + "available.lst"); URLConnection connect = available_url.openConnection(); connect.connect(); InputStream is = connect.getInputStream(); po.setMaximum(connect.getContentLength()); OutputStream os = new FileOutputStream(target); boolean copied = IOUtilities.copyStream(po, is, os, true); if (!copied) { Log.log(Log.ERROR, HunspellDictsManager.class, "Unable to download " + available_url.toString()); GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { "Unable to download file " + available_url.toString() }); availables = null; if (target.exists()) target.delete(); return; } IOUtilities.closeQuietly(os); enc = connect.getContentEncoding(); } FileInputStream fis = new FileInputStream(target); Reader r; if (enc != null) { try { r = new InputStreamReader(fis, enc); } catch (UnsupportedEncodingException uee) { r = new InputStreamReader(fis, "UTF-8"); } } else { r = new InputStreamReader(fis, "UTF-8"); } BufferedReader br = new BufferedReader(r); for (String line = br.readLine(); line != null; line = br.readLine()) { Dictionary d = parseLine(line); if (d != null) { int ind = installed.indexOf(d); if (ind == -1) { d.installed = false; availables.add(d); } else { Dictionary id = installed.get(ind); if (!skipDownload) { Date lmd = fetchLastModifiedDate(id.archiveName); if (lmd != null) { id.lastModified = lmd; } } } } } IOUtilities.closeQuietly(fis); } catch (IOException ioe) { if (ioe instanceof UnknownHostException) { GUIUtilities.error(null, "spell-check-hunspell-error-unknownhost", new String[] { ioe.getMessage() }); } else { GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { ioe.getMessage() }); } ioe.printStackTrace(); if (target.exists()) target.delete(); } } Code Sample 2: public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); }
00
Code Sample 1: @Override public void alterar(QuestaoDiscursiva q) throws Exception { System.out.println("ALTERAR " + q.getIdQuestao()); PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoDiscursiva(q); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HashMap services = configContext.getAxisConfiguration().getServices(); String filePart = req.getRequestURL().toString(); String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length()); if ((services != null) && !services.isEmpty()) { Iterator i = services.values().iterator(); while (i.hasNext()) { AxisService service = (AxisService) i.next(); InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema); if (stream != null) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); IOUtils.copy(stream, out, true); return; } } } }
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 exportDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = input + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); HashMap<Integer, String> languageIDs = new HashMap<Integer, String>(); HashMap<Integer, String> typeIDs = new HashMap<Integer, String>(); long tiempoInicio = System.currentTimeMillis(); Element dataBaseXML = new Element("database"); Element languages = new Element("languages"); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select * from language order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); languageIDs.put(id, name); Element language = new Element("language"); language.setText(name); languages.addContent(language); } dataBaseXML.addContent(languages); rs = stat.executeQuery("select * from type order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); typeIDs.put(id, name); } rs = stat.executeQuery("select distinct name from main order by name"); while (rs.next()) { String name = rs.getString("name"); Element image = new Element("image"); image.setAttribute("id", name); Statement stat2 = G.conn.createStatement(); ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL"); while (rs2.next()) { int idL = rs2.getInt("idL"); Element language = new Element("language"); language.setAttribute("id", languageIDs.get(idL)); Statement stat3 = G.conn.createStatement(); ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT"); while (rs3.next()) { int idT = rs3.getInt("idT"); String word = rs3.getString("word"); Element wordE = new Element("word"); wordE.setAttribute("type", typeIDs.get(idT)); wordE.setText(word); language.addContent(wordE); String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name; String pathDst = output + File.separator + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } rs3.close(); stat3.close(); image.addContent(language); } rs2.close(); stat2.close(); dataBaseXML.addContent(image); } rs.close(); stat.close(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName); out.output(dataBaseXML, f); f.flush(); f.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { } } try { digest.update(data.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { } return encodeHex(digest.digest()); } Code Sample 2: private byte[] odszyfrujKlucz(byte[] kluczSesyjny, int rozmiarKlucza) { byte[] odszyfrowanyKlucz = null; byte[] kluczTymczasowy = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); byte[] tekst = null; kluczTymczasowy = new byte[rozmiarKlucza]; int liczbaBlokow = rozmiarKlucza / ROZMIAR_BLOKU; for (int i = 0; i < liczbaBlokow; i++) { tekst = MARS_Algorithm.blockDecrypt(kluczSesyjny, i * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(tekst, 0, kluczTymczasowy, i * ROZMIAR_BLOKU, tekst.length); } odszyfrowanyKlucz = new byte[dlugoscKlucza]; System.arraycopy(kluczTymczasowy, 0, odszyfrowanyKlucz, 0, dlugoscKlucza); } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return odszyfrowanyKlucz; }
00
Code Sample 1: public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { noSuchAlgorithmException.printStackTrace(); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException unsupportedEncodingException) { unsupportedEncodingException.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } 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 void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: public String login(String nUsuario, String contrasena) { String responce = ""; String request = conf.Conf.login; OutputStreamWriter wr = null; BufferedReader rd = null; try { URL url = new URL(request); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("nUsuario=" + nUsuario + "&contrasena=" + contrasena); wr.flush(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { responce += line; } } catch (Exception e) { } return responce; }
00
Code Sample 1: private void Connect() throws NpsException { try { client = new FTPClient(); client.connect(host.hostname, host.remoteport); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); client = null; nps.util.DefaultLog.error_noexception("FTP Server:" + host.hostname + "refused connection."); return; } client.login(host.uname, host.upasswd); client.enterLocalPassiveMode(); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.changeWorkingDirectory(host.remotedir); } catch (Exception e) { nps.util.DefaultLog.error(e); } } Code Sample 2: public InputStream getResource(FCValue name) throws FCException { Element el = _factory.getElementWithID(name.getAsString()); if (el == null) { throw new FCException("Could not find resource \"" + name + "\""); } String urlString = el.getTextTrim(); if (!urlString.startsWith("http")) { try { log.debug("Get resource: " + urlString); URL url; if (urlString.startsWith("file:")) { url = new URL(urlString); } else { url = getClass().getResource(urlString); } return url.openStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } else { try { FCService http = getRuntime().getServiceFor(FCService.HTTP_DOWNLOAD); return http.perform(new FCValue[] { name }).getAsInputStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } }
11
Code Sample 1: public static String md5String(String string) { try { MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(string.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); String result = ""; for (int i = 0; i < digest.length; i++) { int value = digest[i]; if (value < 0) value += 256; result += Integer.toHexString(value); } return result; } catch (UnsupportedEncodingException error) { throw new IllegalArgumentException(error); } catch (NoSuchAlgorithmException error) { throw new IllegalArgumentException(error); } } Code Sample 2: @SuppressWarnings("unused") private static int chkPasswd(final String sInputPwd, final String sSshaPwd) { assert sInputPwd != null; assert sSshaPwd != null; int r = ERR_LOGIN_ACCOUNT; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); assert ba.length >= FIXED_HASH_SIZE; byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sInputPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); if (MessageDigest.isEqual(hash, baPwdHash)) { r = ERR_LOGIN_OK; } } catch (Exception exc) { exc.printStackTrace(); } return r; }
00
Code Sample 1: private void transferFile(String fileName) throws SocketException, IOException, Exception { FTPClient client = new FTPClient(); client.connect(server.getExternalName(), server.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } client.login(server.getDefaultUserName(), server.getDefaultUserPassword()); reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } InputStream stream = getClass().getClassLoader().getResourceAsStream("res/conf/ftpd.properties"); client.storeFile(fileName, stream); File transfferedFile = new File(server.getServerRootDirectory(), fileName); assertTrue(transfferedFile.exists()); assertTrue(transfferedFile.delete()); } Code Sample 2: @Override public void saveStructure(long userId, TreeStructureInfo info, List<TreeStructureNode> structure) throws DatabaseException { if (info == null) throw new NullPointerException("info"); if (structure == null) throw new NullPointerException("structure"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement insertInfoSt = null, insSt = null; try { insertInfoSt = getConnection().prepareStatement(INSERT_INFO); insertInfoSt.setLong(1, userId); insertInfoSt.setString(2, info.getDescription() != null ? info.getDescription() : ""); insertInfoSt.setString(3, info.getBarcode()); insertInfoSt.setString(4, info.getName()); insertInfoSt.setString(5, info.getInputPath()); insertInfoSt.setString(6, info.getModel()); insertInfoSt.executeUpdate(); PreparedStatement seqSt = getConnection().prepareStatement(INFO_VALUE); ResultSet rs = seqSt.executeQuery(); int key = -1; while (rs.next()) { key = rs.getInt(1); } if (key == -1) { getConnection().rollback(); throw new DatabaseException("Unable to obtain new id from DB when executing query: " + insertInfoSt); } int total = 0; for (TreeStructureNode node : structure) { insSt = getConnection().prepareStatement(INSERT_NODE); insSt.setLong(1, key); insSt.setString(2, node.getPropId()); insSt.setString(3, node.getPropParent()); insSt.setString(4, node.getPropName()); insSt.setString(5, node.getPropPicture()); insSt.setString(6, node.getPropType()); insSt.setString(7, node.getPropTypeId()); insSt.setString(8, node.getPropPageType()); insSt.setString(9, node.getPropDateIssued()); insSt.setString(10, node.getPropAltoPath()); insSt.setString(11, node.getPropOcrPath()); insSt.setBoolean(12, node.getPropExist()); total += insSt.executeUpdate(); } if (total != structure.size()) { getConnection().rollback(); throw new DatabaseException("Unable to insert _ALL_ nodes: " + total + " nodes were inserted of " + structure.size()); } getConnection().commit(); } catch (SQLException e) { LOGGER.error("Queries: \"" + insertInfoSt + "\" and \"" + insSt + "\"", e); } finally { closeConnection(); } }
00
Code Sample 1: private ByteBuffer readProgram(URL url) throws IOException { StringBuilder program = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { program.append(line).append("\n"); } } finally { if (in != null) in.close(); } ByteBuffer buffer = BufferUtils.createByteBuffer(program.length()); for (int i = 0; i < program.length(); i++) { buffer.put((byte) (program.charAt(i) & 0xFF)); } buffer.flip(); return buffer; } Code Sample 2: @MediumTest public void testUrlRewriteRules() throws Exception { ContentResolver resolver = getContext().getContentResolver(); GoogleHttpClient client = new GoogleHttpClient(resolver, "Test", false); Settings.Gservices.putString(resolver, "url:test", "http://foo.bar/ rewrite " + mServerUrl + "new/"); Settings.Gservices.putString(resolver, "digest", mServerUrl); try { HttpGet method = new HttpGet("http://foo.bar/path"); HttpResponse response = client.execute(method); String body = EntityUtils.toString(response.getEntity()); assertEquals("/new/path", body); } finally { client.close(); } }
11
Code Sample 1: private void performDownload() { List<String> selected = filesPane.getSelectedValuesList(); if (selected == null || selected.isEmpty() || selected.size() != 1) { JOptionPane.showMessageDialog(this, "Please select one path"); return; } RFile file = new RFile(selected.get(0)); if (!file.isFile()) { JOptionPane.showMessageDialog(this, "file does not exist anymore"); return; } chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName())); int ok = chooser.showSaveDialog(this); if (ok != JFileChooser.APPROVE_OPTION) { return; } FileOutputStream fout = null; RFileInputStream in = null; try { fout = new FileOutputStream(chooser.getSelectedFile()); in = new RFileInputStream(file); IOUtils.copy(in, fout); JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE); } catch (IOException iOException) { JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } } Code Sample 2: public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: 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; } Code Sample 2: private static String readJarURL(URL url) throws IOException { JarURLConnection juc = (JarURLConnection) url.openConnection(); InputStream in = juc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { out.write(i); i = in.read(); } return out.toString(); }
11
Code Sample 1: @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(); } } } Code Sample 2: @Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } } Code Sample 2: public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } }
00
Code Sample 1: public GridDirectoryList(URL url) throws McIDASException { try { urlc = (AddeURLConnection) url.openConnection(); inputStream = new DataInputStream(new BufferedInputStream(urlc.getInputStream())); } catch (IOException e) { throw new McIDASException("Error opening URL for grids:" + e); } readDirectory(); } Code Sample 2: protected String updateTwitter() { if (updatingTwitter) return null; updatingTwitter = true; String highestId = null; final Cursor cursor = query(TWITTER_TABLE, new String[] { KEY_TWEET_ID }, null, null, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); highestId = cursor.getString(cursor.getColumnIndex(KEY_TWEET_ID)); } cursor.close(); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("screen_name", TWITTER_ACCOUNT)); nameValuePairs.add(new BasicNameValuePair("count", "" + MAX_TWEETS)); if (highestId != null) nameValuePairs.add(new BasicNameValuePair("since_id", highestId)); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); final HttpClient httpclient = new DefaultHttpClient(mgr, params); final HttpGet request = new HttpGet(); final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); String data = ""; try { final URI uri = new URI(TWITTER_URL + "?" + paramString); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ClientProtocolException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final IOException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } try { final JSONArray tweets = new JSONArray(data); if (tweets == null) { updatingTwitter = false; return "failed"; } if (tweets.length() == 0) { updatingTwitter = false; return "none"; } final SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); final SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH); for (int i = 0; i < tweets.length(); i++) { final JSONObject tweet = tweets.getJSONObject(i); final ContentValues values = new ContentValues(); Log.v(TAG, "Datum van tweet: " + tweet.getString(KEY_TWEET_DATE)); values.put(KEY_TWEET_DATE, formatter.format(parser.parse(tweet.getString(KEY_TWEET_DATE)))); values.put(KEY_TWEET_TEXT, tweet.getString(KEY_TWEET_TEXT)); values.put(KEY_TWEET_ID, tweet.getString(KEY_TWEET_ID)); insert(TWITTER_TABLE, values); } } catch (final JSONException e) { Log.v(TAG, "JSON decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ParseException e) { Log.v(TAG, "Datum decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } purgeTweets(); updatingTwitter = false; return "success"; }
11
Code Sample 1: public String fileUpload(final ResourceType type, final String currentFolder, final String fileName, final InputStream inputStream) throws InvalidCurrentFolderException, WriteException { String absolutePath = getRealUserFilesAbsolutePath(RequestCycleHandler.getUserFilesAbsolutePath(ThreadLocalData.getRequest())); File typeDir = getOrCreateResourceTypeDir(absolutePath, type); File currentDir = new File(typeDir, currentFolder); if (!currentDir.exists() || !currentDir.isDirectory()) throw new InvalidCurrentFolderException(); File newFile = new File(currentDir, fileName); File fileToSave = UtilsFile.getUniqueFile(newFile.getAbsoluteFile()); try { IOUtils.copyLarge(inputStream, new FileOutputStream(fileToSave)); } catch (IOException e) { throw new WriteException(); } return fileToSave.getName(); } Code Sample 2: private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: private long config(final String options) throws SQLException { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } msgDigest.update(options.getBytes()); final String md5sum = Concrete.md5(msgDigest.digest()); Statement stmt = connection.createStatement(); ResultSet rst = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + md5sum + "'"); final long configId; if (rst.next()) { configId = rst.getInt(1); } else { stmt.executeUpdate("INSERT INTO configs(config, md5) VALUES ('" + options + "', '" + md5sum + "')"); ResultSet aiRst = stmt.getGeneratedKeys(); if (aiRst.next()) { configId = aiRst.getInt(1); } else { throw new SQLException("Could not retrieve generated id"); } } stmt.executeUpdate("UPDATE executions SET configId=" + configId + " WHERE executionId=" + executionId); return configId; }
11
Code Sample 1: public void trimAndWriteNewSff(OutputStream out) throws IOException { TrimParser trimmer = new TrimParser(); SffParser.parseSFF(untrimmedSffFile, trimmer); tempOut.close(); headerBuilder.withNoIndex().numberOfReads(numberOfTrimmedReads); SffWriter.writeCommonHeader(headerBuilder.build(), out); InputStream in = null; try { in = new FileInputStream(tempReadDataFile); IOUtils.copyLarge(in, out); } finally { IOUtil.closeAndIgnoreErrors(in); } } Code Sample 2: public static void writeToFile(InputStream input, File file, ProgressListener listener, long length) { OutputStream output = null; try { output = new CountingOutputStream(new FileOutputStream(file), listener, length); IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
11
Code Sample 1: public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); } Code Sample 2: JcrFile createBody(Part part) throws IOException, MessagingException { JcrFile body = new JcrFile(); body.setName("part"); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); body.setMimeType(part.getContentType()); body.setLastModified(java.util.Calendar.getInstance()); return body; }
11
Code Sample 1: public String getSummaryText() { if (summaryText == null) { for (Iterator iter = xdcSources.values().iterator(); iter.hasNext(); ) { XdcSource source = (XdcSource) iter.next(); File packageFile = new File(source.getFile().getParentFile(), "xdc-package.html"); if (packageFile.exists()) { 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) { summaryText = buf.substring(pos1 + 6, pos2); } else { summaryText = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); summaryText = ""; } catch (IOException e) { LOG.error(e.getMessage(), e); summaryText = ""; } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } break; } else { summaryText = ""; } } } return summaryText; } Code Sample 2: private void copyIntoFile(String resource, File output) throws IOException { FileOutputStream out = null; InputStream in = null; try { out = FileUtils.openOutputStream(output); in = GroovyInstanceTest.class.getResourceAsStream(resource); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }
00
Code Sample 1: public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) { if (prop == null) { System.err.println("window without properties"); return; } int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Color bgcolor = prop.getValue("bgcolor", Color.white); String caption = prop.getValue("caption", ""); layout = prop.getValue("layout", 0); boolean statusbar = prop.getValue("statusbar", false); if (sheet.opentype == WABSheet.LAYERED) { Point pos = frame.getNextMDIPos(); sheet.setBounds(pos.x, pos.y, 400, 200); sheet.setNormalBounds(new Rectangle(pos.x, pos.y, 400, 200)); } else { sheet.setBounds(x, y, width, height); sheet.setNormalBounds(new Rectangle(x, y, width, height)); } if (sheet.opentype == WABSheet.MAXIMIZED) sheet.setMaximum(true); else sheet.setMaximum(false); sheet.setTitle(caption); frame.addSheetToMenu(caption); sheet.setBackground(bgcolor); if (layout == 1) sheet.getContentPane().setLayout(new FlowLayout()); else if (layout == 2) sheet.getContentPane().setLayout(new BorderLayout()); else sheet.getContentPane().setLayout(null); } else if (tag.equals("menu")) { if (prop == null) { System.err.println("menu without properties"); return; } String id = prop.getValue("id", ""); String label = prop.getValue("label", ""); if ((id != null && id.equals("WINDOW_MENU") || label.equalsIgnoreCase("window"))) { windowMenu = new JMenu(); menu = windowMenu; sheet.setWindowMenu(menu); } else { menu = new JMenu(); } menu.setText(label); sheet.menubar.add(menu); } else if (tag.equals("menuitem")) { if (prop == null) { System.err.println("menuitem without properties"); return; } JMenuItem item; String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); boolean visible = prop.getValue("visible", true); String icon = prop.getValue("icon", ""); if (action.equals("WINDOW_OVERLAPPED")) { item = windowMenuOverlapped = new JMenuItem(); item.setActionCommand("10001"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_HORIZONTALLY")) { item = windowMenuTile = new JMenuItem(); item.setActionCommand("10002"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_VERTICALLY")) { item = windowMenuArrange = new JMenuItem(); item.setActionCommand("10003"); item.addActionListener(frame); } else { item = new JMenuItem(); item.setActionCommand(action); item.addActionListener((WABClient) global); } item.setText(label); if (!visible) menu.setVisible(false); menu.add(item); if (frame.getToolBar() != null) { if (icon.length() > 0) { try { ImageIcon img = new ImageIcon(new URL(icon)); BufferedImage image = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); Graphics g = image.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); BufferedImage pressed = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = pressed.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 5, 5, 16, 16, (ImageObserver) null); g.setColor(new Color(132, 132, 132)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(255, 255, 255)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); BufferedImage over = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = over.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); g.setColor(new Color(255, 255, 255)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(132, 132, 132)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); JButton b = new JButton(new ImageIcon(image)); b.setRolloverEnabled(true); b.setPressedIcon(new ImageIcon(pressed)); b.setRolloverIcon(new ImageIcon(over)); b.setToolTipText(label); b.setActionCommand(action); b.setFocusPainted(false); b.setBorderPainted(false); b.setContentAreaFilled(false); b.setMargin(new Insets(0, 0, 0, 0)); b.addActionListener(sheet); sheet.toolbar.add(b); } catch (Exception e) { } } } } else if (tag.equals("separator")) { menu.addSeparator(); } else if (tag.equals("choice")) { if (prop == null) { System.err.println("choice without properties"); return; } combo = new JComboBox(); list = null; int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); boolean editable = prop.getValue("editable", false); boolean visible = prop.getValue("visible", true); boolean enabled = prop.getValue("enabled", true); combo_text = prop.getValue("text", ""); combo.setBounds(x, y, width, height); combo.setName((String) id); if (editable) { combo.setEditable(editable); combo.setSelectedItem(combo_text); } if (!visible) combo.setVisible(false); if (!enabled) combo.setEnabled(false); if (layout == 0) sheet.getContentPane().add(combo); else sheet.getContentPane().add(combo, constraints); } else if (tag.equals("list")) { if (prop == null) { System.err.println("list without properties"); return; } list = new JList(); combo = null; listdata = new Vector(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); list.setName((String) id); list.setListData(listdata); JScrollPane sp = new JScrollPane(list); sp.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(sp); else sheet.getContentPane().add(sp, constraints); } else if (tag.equals("option")) { if (prop == null) { System.err.println("choice.option without properties"); return; } String value = prop.getValue("value", ""); String text = prop.getValue("text", ""); if (list != null) listdata.addElement(new ComboOption(text, value)); if (combo != null) { ComboOption co = new ComboOption(text, value); combo.addItem(co); if (combo_text.equals(text.trim())) combo.setSelectedItem(co); } } else if (tag.equals("label")) { if (prop == null) { System.err.println("label without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); boolean visible = prop.getValue("visible", true); label.setBounds(x, y, width, height); label.setText(text); if (!visible) label.setVisible(false); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("button")) { if (prop == null) { System.err.println("button without properties"); return; } JButton btn = new JButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); btn.setBounds(x, y, width, height); btn.setText(text); btn.addActionListener(sheet); btn.setActionCommand(onmouseup); if (layout == 0) sheet.getContentPane().add(btn); else sheet.getContentPane().add(btn, constraints); } else if (tag.equals("radiobutton")) { if (prop == null) { System.err.println("radiobutton without properties"); return; } JRadioButton rb = new JRadioButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); rb.setBounds(x, y, width, height); rb.setText(text); rb.setName((String) id); rb.addActionListener(sheet); rb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(rb); else sheet.getContentPane().add(rb, constraints); } else if (tag.equals("checkbox")) { if (prop == null) { System.err.println("checkbox without properties"); return; } JCheckBox cb = new JCheckBox(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); cb.setBounds(x, y, width, height); cb.setText(text); cb.setName((String) id); cb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(cb); else sheet.getContentPane().add(cb, constraints); } else if (tag.equals("image")) { if (prop == null) { System.err.println("image without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String src = prop.getValue("src", ""); Object constraints = prop.getValue("constraints"); label.setIcon(new ImageIcon(new URL(src))); label.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("singlelineedit")) { if (prop == null) { System.err.println("singlelineedit without properties"); return; } String pwd = prop.getValue("password", ""); JTextField sle; if (pwd.equalsIgnoreCase("true")) sle = new JPasswordField(); else sle = new JTextField(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Object id = prop.getValue("id"); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); sle.setBounds(x, y, width, height); sle.setText(text); sle.setName((String) id); if (layout == 0) sheet.getContentPane().add(sle); else sheet.getContentPane().add(sle, constraints); } else if (tag.equals("treeview")) { if (prop == null) { System.err.println("treeview without properties"); return; } treeview_root = new DefaultMutableTreeNode("root"); treeview = new JTree(treeview_root); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(treeview), constraints); } else if (tag.equals("treeitem")) { if (prop == null) { System.err.println("treeview.treeitem without properties"); return; } String text = prop.getValue("text", ""); String value = prop.getValue("value", ""); DefaultMutableTreeNode node = new DefaultMutableTreeNode(text); treeview_root.add(node); } else if (tag.equals("table")) { if (prop == null) { System.err.println("table without properties"); return; } String id = prop.getValue("id", ""); table = new JTable(); model = new DefaultTableModel() { public boolean isCellEditable(int row, int col) { return false; } }; table.setModel(model); table.setName((String) id); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(table), constraints); rowNumber = 0; columnNumber = 0; headerWidths = new Vector(); } else if (tag.equals("header")) { if (prop == null) { System.err.println("table.header without properties"); return; } String text = prop.getValue("text", ""); int width = prop.getValue("width", 0); headerWidths.addElement(new Integer(width)); model.addColumn(text); } else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.setRowCount(rowNumber); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("script")) { sheet.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; sheet.script += buffer + "\n"; } r.close(); sheet.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[sheet] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } } Code Sample 2: private boolean dependencyOutOfDate(ScriptCacheEntry entry) { if (entry != null) { for (Iterator i = entry.dependencies.keySet().iterator(); i.hasNext(); ) { URLConnection urlc = null; URL url = (URL) i.next(); try { urlc = url.openConnection(); urlc.setDoInput(false); urlc.setDoOutput(false); long dependentLastModified = urlc.getLastModified(); if (dependentLastModified > ((Long) entry.dependencies.get(url)).longValue()) { return true; } } catch (IOException ioe) { return true; } } } return false; }
00
Code Sample 1: private static String getDigestPassword(String streamId, String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw (RuntimeException) new IllegalStateException().initCause(e); } md.update((streamId + password).getBytes()); byte[] uid = md.digest(); int length = uid.length; StringBuilder digPass = new StringBuilder(); for (int i = 0; i < length; ) { int k = uid[i++]; int iint = k & 0xff; String buf = Integer.toHexString(iint); if (buf.length() == 1) { buf = "0" + buf; } digPass.append(buf); } return digPass.toString(); } Code Sample 2: private static void _readAllRegionMDFiles(ClassLoader loader, RegionMetadata bean, String regionMDFile) { if (_LOG.isFinest()) { _LOG.finest("searching for region-metadata with resource:{0}", regionMDFile); } try { Enumeration<URL> files = loader.getResources(regionMDFile); while (files.hasMoreElements()) { URL url = files.nextElement(); String publicId = url.toString(); try { InputStream in = url.openStream(); _readRegionMetadata(bean, in, publicId); in.close(); } catch (IOException e) { _error(publicId, e); } } } catch (IOException e) { _LOG.warning("ERR_GET_REGION_METADATA_FILE", __CONFIG_FILE_OTHER); _LOG.warning(e); } }
00
Code Sample 1: private String getSearchResults(String id) { try { final URL url = new URL("http://www.jaap.nl/api/jaapAPI.do?clientId=iPhone&limit=5&request=details&id=" + id + "&format=JSON&field=street_nr&field=zip&field=city&field=price&field=thumb&field=since&field=houseType&field=area&field=rooms&field=id"); final StringBuilder builder = new StringBuilder(); final BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream())); String s = ""; while ((s = rd.readLine()) != null) { builder.append(s); } rd.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: public int getHttpStatus(ProxyInfo proxyInfo, String sUrl, String cookie, String host) { HttpURLConnection connection = null; try { if (proxyInfo == null) { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); } else { InetSocketAddress addr = new InetSocketAddress(proxyInfo.getPxIp(), proxyInfo.getPxPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(proxy); } if (!isStringNull(host)) setHttpInfo(connection, cookie, host, ""); connection.setConnectTimeout(90 * 1000); connection.setReadTimeout(90 * 1000); connection.connect(); connection.getInputStream(); return connection.getResponseCode(); } catch (IOException e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } catch (Exception e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } }
00
Code Sample 1: public void movePrior(String[] showOrder, String[] orgID, String targetShowOrder, String targetOrgID) throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; int moveCount = showOrder.length; DBOperation dbo = factory.createDBOperation(POOL_NAME); String strQuery = "select show_order from " + Common.ORGANIZE_TABLE + " where show_order=" + showOrder[moveCount - 1] + " and organize_id= '" + orgID[moveCount - 1] + "'"; try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strQuery); result = ps.executeQuery(); int maxOrderNo = 0; if (result.next()) { maxOrderNo = result.getInt(1); } String[] sqls = new String[moveCount + 1]; sqls[0] = "update " + Common.ORGANIZE_TABLE + " set show_order=" + maxOrderNo + " where show_order=" + targetShowOrder + " and organize_id= '" + targetOrgID + "'"; for (int i = 0; i < showOrder.length; i++) { sqls[i + 1] = "update " + Common.ORGANIZE_TABLE + " set show_order=show_order-1" + " where show_order=" + showOrder[i] + " and organize_id= '" + orgID[i] + "'"; } for (int j = 0; j < sqls.length; j++) { ps = con.prepareStatement(sqls[j]); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new CesSystemException("Organize.movePrior(): ERROR Inserting data " + "in T_SYS_ORGANIZE update !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { if (con != null) { con.rollback(); } throw new CesSystemException("Organize.movePrior(): SQLException while mov organize order " + " :\n\t" + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } 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 main(String[] arg) throws IOException { XmlPullParserFactory PULL_PARSER_FACTORY; try { PULL_PARSER_FACTORY = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); PULL_PARSER_FACTORY.setNamespaceAware(true); DasParser dp = new DasParser(PULL_PARSER_FACTORY); URL url = new URL("http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/features?segment=P05067"); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String aLine, xml = ""; while ((aLine = br.readLine()) != null) { xml += aLine; } WritebackDocument wbd = dp.parse(xml); System.out.println("FIN" + wbd); } catch (XmlPullParserException xppe) { throw new IllegalStateException("Fatal Exception thrown at initialisation. Cannot initialise the PullParserFactory required to allow generation of the DAS XML.", xppe); } } Code Sample 2: public String excute(String targetUrl, String params, String type) { URL url; HttpURLConnection connection = null; try { url = new URL(targetUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); connection.setRequestProperty("Content-Language", CHAR_SET); connection.setRequestProperty("Connection", "close"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (params != null) { if (params.length() > 0) { DataOutputStream wr; wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); } } InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, CHAR_SET)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append("\r\n"); } rd.close(); return response.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static String hashPassword(String password) { String passwordHash = ""; try { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); sha1.reset(); sha1.update(password.getBytes()); Base64 encoder = new Base64(); passwordHash = new String(encoder.encode(sha1.digest())); } catch (NoSuchAlgorithmException e) { LoggerFactory.getLogger(UmsAuthenticationProcessingFilter.class.getClass()).error("Failed to generate password hash: " + e.getMessage()); } return passwordHash; } Code Sample 2: @Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (Exception e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } }
11
Code Sample 1: private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
11
Code Sample 1: public void sendResponse(DjdocRequest req, HttpServletResponse res) throws IOException { File file = (File) req.getResult(); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) { in.close(); } } } Code Sample 2: @Override public void dispatchContent(InputStream is) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Sending content message over JMS"); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); this.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { BytesMessage message = session.createBytesMessage(); message.writeBytes(bos.toByteArray()); return message; } }); }
00
Code Sample 1: public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: private void postUrl() throws Exception { String authors = ""; for (String auth : plugin.getDescription().getAuthors()) { authors = authors + " " + auth; } authors = authors.trim(); String url = String.format("http://bukkitstats.randomappdev.com/ping.aspx?snam=%s&sprt=%s&shsh=%s&sver=%s&spcnt=%s&pnam=%s&pmcla=%s&paut=%s&pweb=%s&pver=%s", URLEncoder.encode(plugin.getServer().getName(), "UTF-8"), plugin.getServer().getPort(), hash, URLEncoder.encode(Bukkit.getVersion(), "UTF-8"), plugin.getServer().getOnlinePlayers().length, URLEncoder.encode(plugin.getDescription().getName(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getMain(), "UTF-8"), URLEncoder.encode(authors, "UTF-8"), URLEncoder.encode(plugin.getDescription().getWebsite(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getVersion(), "UTF-8")); new URL(url).openConnection().getInputStream(); }
00
Code Sample 1: private BibtexDatabase importInspireEntries(String key, OutputPrinter frame) { String url = constructUrl(key); try { HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Jabref"); InputStream inputStream = conn.getInputStream(); INSPIREBibtexFilterReader reader = new INSPIREBibtexFilterReader(new InputStreamReader(inputStream)); ParserResult pr = BibtexParser.parse(reader); return pr.getDatabase(); } catch (IOException e) { frame.showMessage(Globals.lang("An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (RuntimeException e) { frame.showMessage(Globals.lang("An Error occurred while fetching from INSPIRE source (%0):", new String[] { url }) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } return null; } Code Sample 2: public synchronized String encrypt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: 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; } Code Sample 2: public static Builder fromURL(URL url) { try { InputStream in = null; try { in = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read = -1; byte[] buf = new byte[4096]; while ((read = in.read(buf)) >= 0) { if (read > 0) { baos.write(buf, 0, read); } } StreamBuilder b = (StreamBuilder) fromMemory(baos.toByteArray()); try { b.setSystemId(url.toURI().toString()); } catch (URISyntaxException use) { b.setSystemId(url.toString()); } return b; } finally { if (in != null) { in.close(); } } } catch (IOException ex) { throw new XMLUnitException(ex); } }
11
Code Sample 1: public static Map<String, File> extractFiles(String input, File tempDirectory) throws IOException { byte data[] = new byte[BUFFER]; BufferedOutputStream out = null; FileInputStream src = new FileInputStream(input); BufferedInputStream in = new BufferedInputStream(src); ZipInputStream zipin = new ZipInputStream(in); Map<String, File> files = new HashMap<String, File>(); ZipEntry entry; while ((entry = zipin.getNextEntry()) != null) { logger.info(TAG + ": entr�e " + entry.getName() + " r�pertoire ? " + entry.isDirectory()); if (entry.isDirectory()) { logger.info(TAG + ": Ajout de l'entr�e pour le r�pertoire: " + entry.getName()); files.put(entry.getName(), extractDirectory(entry.getName(), zipin, tempDirectory)); File f = files.get(entry.getName()); if (f == null) logger.info(TAG + ": NULLL: "); continue; } File tempFile = new File(tempDirectory, entry.getName()); if (tempFile.exists()) tempFile.delete(); tempFile.createNewFile(); FileOutputStream dest = new FileOutputStream(tempFile); out = new BufferedOutputStream(dest, BUFFER); int count; for (int c = zipin.read(); c != -1; c = zipin.read()) dest.write(c); logger.info(TAG + ": Ajout de l'entr�e: " + entry.getName() + " du fichier: " + tempFile.getAbsolutePath()); files.put(entry.getName(), tempFile); out.close(); dest.close(); } zipin.close(); in.close(); src.close(); return files; } Code Sample 2: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
00
Code Sample 1: private boolean postLogin() { URL url = null; URLConnection urlConn = null; OutputStream out = null; int code = 0; boolean gotPhpsessid = false; try { url = new URL("http://" + m_host + "/forums/index.php?action=login2"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("POST"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); out = urlConn.getOutputStream(); out.write(new String("user=" + m_username + "&passwrd=" + m_password + "&cookielength=60").getBytes()); out.flush(); out.close(); do { readCookies(urlConn); m_referer = url.toString(); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code == 301 || code == 302) { url = new URL(urlConn.getHeaderField("Location")); urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); continue; } if (code == 200) { String refreshHdr = urlConn.getHeaderField("Refresh"); Pattern p_phpsessid = Pattern.compile(".*?\\?PHPSESSID=(\\w+).*"); Matcher match_phpsessid = p_phpsessid.matcher(refreshHdr); if (match_phpsessid.matches()) { gotPhpsessid = true; } urlConn = null; continue; } String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } while (urlConn != null); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotPhpsessid) { m_turnSummaryRef = "Error: PHPSESSID not found after login. "; return false; } if (m_cookies == null) { m_turnSummaryRef = "Error: cookies not found after login. "; return false; } try { Thread.sleep(m_loginDelayInSeconds * 1000); } catch (InterruptedException ie) { ie.printStackTrace(); } return true; } 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(); } }
00
Code Sample 1: private static void checkClients() { try { sendMultiListEntry('l'); } catch (Exception e) { if (Util.getDebugLevel() > 90) e.printStackTrace(); } try { if (CANT_CHECK_CLIENTS != null) KeyboardHero.removeStatus(CANT_CHECK_CLIENTS); URL url = new URL(URL_STR + "?req=clients" + (server != null ? "&port=" + server.getLocalPort() : "")); URLConnection connection = url.openConnection(getProxy()); connection.setRequestProperty("User-Agent", USER_AGENT); BufferedReader bufferedRdr = new BufferedReader(new InputStreamReader(connection.getInputStream())); String ln; if (Util.getDebugLevel() > 30) Util.debug("URL: " + url); while ((ln = bufferedRdr.readLine()) != null) { String[] parts = ln.split(":", 2); if (parts.length < 2) { Util.debug(12, "Line read in checkClients: " + ln); continue; } try { InetSocketAddress address = new InetSocketAddress(parts[0], Integer.parseInt(parts[1])); boolean notFound = true; if (Util.getDebugLevel() > 25) Util.debug("NEW Address: " + address.toString()); synchronized (clients) { Iterator<Client> iterator = clients.iterator(); while (iterator.hasNext()) { final Client client = iterator.next(); if (client.socket.isClosed()) { iterator.remove(); continue; } if (Util.getDebugLevel() > 26 && client.address != null) Util.debug("Address: " + client.address.toString()); if (address.equals(client.address)) { notFound = false; break; } } } if (notFound) { connectClient(address); } } catch (NumberFormatException e) { } } bufferedRdr.close(); } catch (MalformedURLException e) { Util.conditionalError(PORT_IN_USE, "Err_PortInUse"); Util.error(Util.getMsg("Err_CantCheckClients")); } catch (FileNotFoundException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), Util.getMsg("Err_FileNotFound")); } catch (SocketException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), e.getLocalizedMessage()); } catch (Exception e) { CANT_CHECK_CLIENTS.setException(e.toString()); KeyboardHero.addStatus(CANT_CHECK_CLIENTS); } } 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 void setTypeRefs(Connection conn) { log.traceln("\tProcessing " + table + " references.."); try { String query = " select distinct c.id, c.qualifiedname from " + table + ", CLASSTYPE c " + " where " + table + "." + reffield + " is null and " + table + "." + classnamefield + " = c.qualifiedname"; PreparedStatement pstmt = conn.prepareStatement(query); long start = new Date().getTime(); ResultSet rset = pstmt.executeQuery(); long queryTime = new Date().getTime() - start; log.debug("query time: " + queryTime + " ms"); String update = "update " + table + " set " + reffield + "=? where " + classnamefield + "=? and " + reffield + " is null"; PreparedStatement pstmt2 = conn.prepareStatement(update); int n = 0; start = new Date().getTime(); while (rset.next()) { n++; pstmt2.setInt(1, rset.getInt(1)); pstmt2.setString(2, rset.getString(2)); pstmt2.executeUpdate(); } queryTime = new Date().getTime() - start; log.debug("total update time: " + queryTime + " ms"); log.debug("number of times through loop: " + n); if (n > 0) log.debug("avg update time: " + (queryTime / n) + " ms"); pstmt2.close(); rset.close(); pstmt.close(); conn.commit(); log.verbose("Updated (committed) " + table + " references"); } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } } 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); } }
00
Code Sample 1: private static void download(String urlString) throws IOException { URL url = new URL(urlString); url = handleRedirectUrl(url); URLConnection cn = url.openConnection(); Utils.setHeader(cn); long fileLength = cn.getContentLength(); Statics.getInstance().setFileLength(fileLength); long packageLength = fileLength / THREAD_COUNT; long leftLength = fileLength % THREAD_COUNT; String fileName = Utils.decodeURLFileName(url); RandomAccessFile file = new RandomAccessFile(fileName, "rw"); System.out.println("File: " + fileName + ", Size: " + Utils.calSize(fileLength)); CountDownLatch latch = new CountDownLatch(THREAD_COUNT + 1); long pos = 0; for (int i = 0; i < THREAD_COUNT; i++) { long endPos = pos + packageLength; if (leftLength > 0) { endPos++; leftLength--; } new Thread(new DownloadThread(latch, url, file, pos, endPos)).start(); pos = endPos; } new Thread(new MoniterThread(latch)).start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(String input, String output) { try { File inputFile = new File(input); File outputFile = new File(output); FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public boolean actualizarIdPartida(int idJugadorDiv, int idRonda, int idPartida) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: private String loadStatusResult() { try { URL url = new URL(getServerUrl()); InputStream input = url.openStream(); InputStreamReader is = new InputStreamReader(input, "utf-8"); BufferedReader reader = new BufferedReader(is); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e1) { e1.printStackTrace(); return null; } catch (IOException e2) { e2.printStackTrace(); return null; } }
00
Code Sample 1: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); } Code Sample 2: public PollSetMessage(String username, String question, String title, String[] choices) { this.username = username; MessageDigest m = null; try { m = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } String id = username + String.valueOf(System.nanoTime()); m.update(id.getBytes(), 0, id.length()); voteId = new BigInteger(1, m.digest()).toString(16); this.question = question; this.title = title; this.choices = choices; }
11
Code Sample 1: boolean createSessionArchive(String archiveFilename) { byte[] buffer = new byte[1024]; try { ZipOutputStream archive = new ZipOutputStream(new FileOutputStream(archiveFilename)); for (mAnnotationsCursor.moveToFirst(); !mAnnotationsCursor.isAfterLast(); mAnnotationsCursor.moveToNext()) { FileInputStream in = new FileInputStream(mAnnotationsCursor.getString(ANNOTATIONS_FILE_NAME)); archive.putNextEntry(new ZipEntry("audio" + (mAnnotationsCursor.getPosition() + 1) + ".3gpp")); int length; while ((length = in.read(buffer)) > 0) archive.write(buffer, 0, length); archive.closeEntry(); in.close(); } archive.close(); } catch (IOException e) { Toast.makeText(mActivity, mActivity.getString(R.string.error_zip) + " " + e.getMessage(), Toast.LENGTH_SHORT).show(); return false; } return true; } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
11
Code Sample 1: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } } Code Sample 2: private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } }
00
Code Sample 1: public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } } Code Sample 2: public static Set<Address> getDatosCatastrales(String pURL) { Set<Address> result = new HashSet<Address>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniInm1 = "<rcdnp>"; String finInm1 = "</rcdnp>"; String iniInm2 = "<bi>"; String finInm2 = "</bi>"; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniCar = "<car>"; String finCar = "</car>"; String iniCC1 = "<cc1>"; String finCC1 = "</cc1>"; String iniCC2 = "<cc2>"; String finCC2 = "</cc2>"; String iniLDT = "<ldt>"; String iniBq = "<bq>"; String finBq = "</bq>"; String iniEs = "<es>"; String finEs = "</es>"; String iniPt = "<pt>"; String finPt = "</pt>"; String iniPu = "<pu>"; String finPu = "</pu>"; boolean error = false; int ini, fin; int postal = 0; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniInm1) || str.contains(iniInm2)) { Address inmueble = new Address(); while ((str = br.readLine()) != null && !str.contains(finInm1) && !str.contains(finInm2)) { if (str.contains(iniPC1) && str.contains(finPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); inmueble.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2) && str.contains(finPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniLDT) && str.contains("-")) { postal = Integer.parseInt(str.substring(str.lastIndexOf("-") - 5, str.lastIndexOf("-"))); } if (str.contains(iniCar) && str.contains(finCar)) { ini = str.indexOf(iniCar) + iniCar.length(); fin = str.indexOf(finCar); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC1) && str.contains(finCC1)) { ini = str.indexOf(iniCC1) + iniCC1.length(); fin = str.indexOf(finCC1); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC2) && str.contains(finCC2)) { ini = str.indexOf(iniCC2) + iniCC2.length(); fin = str.indexOf(finCC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniBq) && str.contains(finBq)) { ini = str.indexOf(iniBq) + iniBq.length(); fin = str.indexOf(finBq); inmueble.setBlock(str.substring(ini, fin)); } if (str.contains(iniEs) && str.contains(finEs)) { ini = str.indexOf(iniEs) + iniEs.length(); fin = str.indexOf(finEs); inmueble.setStairs(str.substring(ini, fin)); } if (str.contains(iniPt) && str.contains(finPt)) { ini = str.indexOf(iniPt) + iniPt.length(); fin = str.indexOf(finPt); inmueble.setFloor(str.substring(ini, fin)); } if (str.contains(iniPu) && str.contains(finPu)) { ini = str.indexOf(iniPu) + iniPu.length(); fin = str.indexOf(finPu); inmueble.setDoor(str.substring(ini, fin)); } } result.add(inmueble); } } } br.close(); if (result.size() == 1) { Object ad[] = result.toArray(); Coordinate coord = ConversorCoordenadas.getCoordenadas(((Address) ad[0]).getDescription()); coord.setPostcode(postal); for (Address inm : result) inm.setCoodinate(coord); } } catch (Exception e) { System.err.println(e); } return result; }
00
Code Sample 1: public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } Code Sample 2: public File convert(URI uri) throws DjatokaException { processing.add(uri.toString()); File urlLocal = null; try { logger.info("processingRemoteURI: " + uri.toURL()); boolean isJp2 = false; InputStream src = IOUtils.getInputStream(uri.toURL()); String ext = uri.toURL().toString().substring(uri.toURL().toString().lastIndexOf(".") + 1).toLowerCase(); if (ext.equals(FORMAT_ID_TIF) || ext.equals(FORMAT_ID_TIFF)) { urlLocal = File.createTempFile("convert" + uri.hashCode(), "." + FORMAT_ID_TIF); } else if (formatMap.containsKey(ext) && (formatMap.get(ext).equals(FORMAT_MIMEYPE_JP2) || formatMap.get(ext).equals(FORMAT_MIMEYPE_JPX))) { urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + ext); isJp2 = true; } else { if (src.markSupported()) src.mark(15); if (ImageProcessingUtils.checkIfJp2(src)) urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + FORMAT_ID_JP2); if (src.markSupported()) src.reset(); else { src.close(); src = IOUtils.getInputStream(uri.toURL()); } } if (urlLocal == null) { urlLocal = File.createTempFile("convert" + uri.hashCode(), ".img"); } urlLocal.deleteOnExit(); FileOutputStream dest = new FileOutputStream(urlLocal); IOUtils.copyStream(src, dest); if (!isJp2) urlLocal = processImage(urlLocal, uri); src.close(); dest.close(); return urlLocal; } catch (Exception e) { urlLocal.delete(); throw new DjatokaException(e); } finally { if (processing.contains(uri.toString())) processing.remove(uri.toString()); } }
00
Code Sample 1: @Override public void alterar(QuestaoDiscursiva q) throws Exception { System.out.println("ALTERAR " + q.getIdQuestao()); PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoDiscursiva(q); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: protected void unZip() throws PersistenceException { boolean newZip = false; try { if (null == backup) { mode = (String) context.get(Context.MODE); if (null == mode) mode = Context.MODE_NAME_RESTORE; backupDirectory = (File) context.get(Context.BACKUP_DIRECTORY); logger.debug("Got backup directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backupDirectory.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backupDirectory.mkdirs(); } else if (!backupDirectory.exists()) { throw new PersistenceException("Backup directory {" + backupDirectory.getAbsolutePath() + "} does not exist."); } backup = new File(backupDirectory + "/" + getBackupName() + ".zip"); logger.debug("Got zip file {" + backup.getAbsolutePath() + "}"); } File _explodedDirectory = File.createTempFile("exploded-" + backup.getName() + "-", ".zip"); _explodedDirectory.mkdirs(); _explodedDirectory.delete(); backupDirectory = new File(_explodedDirectory.getParentFile(), _explodedDirectory.getName()); backupDirectory.mkdirs(); logger.debug("Created exploded directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backup.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backup.createNewFile(); } else if (!backup.exists()) { throw new PersistenceException("Backup file {" + backup.getAbsolutePath() + "} does not exist."); } if (newZip) return; ZipFile zip = new ZipFile(backup); Enumeration zipFileEntries = zip.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); logger.debug("Inflating: " + entry); File destFile = new File(backupDirectory, currentEntry); File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); if (!entry.isDirectory()) { InputStream in = null; OutputStream out = null; try { in = zip.getInputStream(entry); out = new FileOutputStream(destFile); IOUtils.copy(in, out); } finally { if (null != out) out.close(); if (null != in) in.close(); } } } } catch (IOException e) { logger.error("Unable to unzip {" + backup + "}", e); throw new PersistenceException(e); } }
11
Code Sample 1: public static void copyFile(File in, File out) throws EnhancedException { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (Exception e) { throw new EnhancedException("Could not copy file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + ".", e); } } Code Sample 2: public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
11
Code Sample 1: public static void copy(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); }
11
Code Sample 1: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } Code Sample 2: public void run() { Pair p = null; try { while ((p = queue.pop()) != null) { GetMethod get = new GetMethod(p.getRemoteUri()); try { get.setFollowRedirects(true); get.setRequestHeader("Mariner-Application", "prerenderer"); get.setRequestHeader("Mariner-DeviceName", deviceName); int iGetResultCode = httpClient.executeMethod(get); if (iGetResultCode != 200) { throw new IOException("Got response code " + iGetResultCode + " for a request for " + p.getRemoteUri()); } InputStream is = get.getResponseBodyAsStream(); File localFile = new File(deviceFile, p.getLocalUri()); localFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(localFile); IOUtils.copy(is, os); os.close(); } finally { get.releaseConnection(); } } } catch (Exception ex) { result = ex; } }
00
Code Sample 1: public static StringBuffer getCachedFile(String url) throws Exception { File urlCache = new File("tmp-cache/" + url.replace('/', '-')); new File("tmp-cache/").mkdir(); if (urlCache.exists()) { BufferedReader in = new BufferedReader(new FileReader(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); } in.close(); return buffer; } else { URL url2 = new URL(url.replace(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream())); BufferedWriter cacheWriter = new BufferedWriter(new FileWriter(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); cacheWriter.write(input + "\n"); } cacheWriter.close(); in.close(); return buffer; } } Code Sample 2: 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); }
00
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: private InputStream getPart() throws IOException { HttpGet get = new HttpGet(url); get.addHeader("Range", "bytes=" + startAt + "-"); HttpResponse res = client.execute(get); System.out.println("requesting kBs from " + startAt + " server reply:" + res.getStatusLine()); if (res.getStatusLine().getStatusCode() == 403 || res.getStatusLine().toString().toLowerCase().contains("forbidden")) { get.abort(); get = new HttpGet(url); get.addHeader("Range", "bytes=" + startAt + "-" + (startAt + downLimit)); res = client.execute(get); System.out.println("Again requesting from kBs " + startAt + " server reply:" + res.getStatusLine()); startAt += downLimit; } else { complete = true; } return res.getEntity() == null ? null : res.getEntity().getContent(); }
11
Code Sample 1: private void serializeWithClass(Class theClass, int count, String comment) { for (int c = 0; c < 10; c++) { if (c == 9) { beginAction(1, "persistence write/read", count, comment); } String tempFile = ".tmp.archive"; SerializeClassInterface theInstance = null; try { theInstance = (SerializeClassInterface) theClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } if (theInstance == null) { System.err.println("error: Couldn't initialize class to " + "be serialized!"); return; } reset(); for (int i = 0; i < count; i++) { try { FileOutputStream fout = new FileOutputStream(tempFile); BufferedOutputStream bout = new BufferedOutputStream(fout); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(theInstance); oout.flush(); oout.close(); } catch (IOException ioe) { System.err.println("serializing: " + tempFile + ":" + ioe.toString()); } try { FileInputStream fin = new FileInputStream(tempFile); BufferedInputStream bin = new BufferedInputStream(fin); ObjectInputStream oin = new ObjectInputStream(bin); theInstance = (SerializeClassInterface) oin.readObject(); oin.close(); } catch (Exception e) { System.err.println("deserializing: " + tempFile + ":" + e.toString()); break; } proceed(); } reset(); if (c == 9) { endAction(); } } } Code Sample 2: private static boolean genCustomerLocationsFileAndCustomerIndexFile(String completePath, String masterFile, String CustLocationsFileName, String CustIndexFileName) { try { TIntObjectHashMap CustInfoHash = new TIntObjectHashMap(480189, 1); File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC = new FileInputStream(inFile).getChannel(); File outFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel outC1 = new FileOutputStream(outFile1, true).getChannel(); File outFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel outC2 = new FileOutputStream(outFile2, true).getChannel(); int fileSize = (int) inC.size(); int totalNoDataRows = fileSize / 7; for (int i = 1; i <= totalNoDataRows; i++) { ByteBuffer mappedBuffer = ByteBuffer.allocate(7); inC.read(mappedBuffer); mappedBuffer.position(0); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); mappedBuffer.clear(); if (CustInfoHash.containsKey(customer)) { TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); locations.add(i); CustInfoHash.put(customer, locations); } else { TIntArrayList locations = new TIntArrayList(); locations.add(i); CustInfoHash.put(customer, locations); } } int[] customers = CustInfoHash.keys(); Arrays.sort(customers); int count = 1; for (int i = 0; i < customers.length; i++) { int customer = customers[i]; TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); int noRatingsForCust = locations.size(); ByteBuffer outBuf1 = ByteBuffer.allocate(12); outBuf1.putInt(customer); outBuf1.putInt(count); outBuf1.putInt(count + noRatingsForCust - 1); outBuf1.flip(); outC1.write(outBuf1); count += noRatingsForCust; for (int j = 0; j < locations.size(); j++) { ByteBuffer outBuf2 = ByteBuffer.allocate(4); outBuf2.putInt(locations.get(j)); outBuf2.flip(); outC2.write(outBuf2); } } inC.close(); outC1.close(); outC2.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
11
Code Sample 1: private static void generateFile(String inputFilename, String outputFilename) throws Exception { File inputFile = new File(inputFilename); if (inputFile.exists() == false) { throw new Exception(Messages.getString("ScriptDocToBinary.Input_File_Does_Not_Exist") + inputFilename); } Environment environment = new Environment(); environment.initBuiltInObjects(); NativeObjectsReader reader = new NativeObjectsReader(environment); InputStream input = new FileInputStream(inputFile); System.out.println(Messages.getString("ScriptDocToBinary.Reading_Documentation") + inputFilename); reader.loadXML(input); checkFile(outputFilename); File binaryFile = new File(outputFilename); FileOutputStream outputStream = new FileOutputStream(binaryFile); TabledOutputStream output = new TabledOutputStream(outputStream); reader.getScriptDoc().write(output); output.close(); System.out.println(Messages.getString("ScriptDocToBinary.Finished")); System.out.println(); } 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: public static InputStream openStream(URL url) { try { URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); } catch (IOException e) { throw new IORuntimeException(e); } } Code Sample 2: @Override public void run() { String url = "http://" + resources.getString(R.string.host) + path; HttpUriRequest req; if (dataToSend == null) { req = new HttpGet(url); } else { req = new HttpPost(url); try { ((HttpPost) req).setEntity(new StringEntity(dataToSend)); } catch (UnsupportedEncodingException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.SEVERE, "Unsupported encoding.", e); } } req.addHeader("Cookie", getAuthCookie(false)); try { HttpResponse response = httpclient.execute(req); Logger.getLogger(JSBridge.class.getName()).log(Level.INFO, "Response status is '" + response.getStatusLine() + "'."); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { BufferedReader in = new BufferedReader(new InputStreamReader(instream)); StringBuilder b = new StringBuilder(); String line; boolean first = true; while ((line = in.readLine()) != null) { b.append(line); if (first) { first = false; } else { b.append("\r\n"); } } in.close(); callback.success(b.toString()); return; } catch (RuntimeException ex) { throw ex; } finally { instream.close(); } } } catch (ClientProtocolException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.SEVERE, "HTTP protocol violated.", e); } catch (IOException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.WARNING, "Could not load '" + path + "'.", e); } Logger.getLogger(JSBridge.class.getName()).log(Level.INFO, "Calling error from JSBridge.getPage because of previous errors."); callback.error(); }
00
Code Sample 1: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } Code Sample 2: private InputStream loadFromUrl(URL url, String contentType) throws IOException { Proxy proxy = null; if (isUseProxy) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } else { proxy = Proxy.NO_PROXY; } URLConnection connection = url.openConnection(proxy); connection.setRequestProperty("Accept-Charset", DEFAULT_CHARSET); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("User-Agent", USER_AGENT); InputStream response = connection.getInputStream(); return response; }
11
Code Sample 1: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } Code Sample 2: public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } 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: protected void shutdown(final boolean unexpected) { ControlerState oldState = this.state; this.state = ControlerState.Shutdown; if (oldState == ControlerState.Running) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } this.controlerListenerManager.fireControlerShutdownEvent(unexpected); if (this.dumpDataAtEnd) { Knowledges kk; if (this.config.scenario().isUseKnowledges()) { kk = (this.getScenario()).getKnowledges(); } else { kk = this.getScenario().retrieveNotEnabledKnowledges(); } new PopulationWriter(this.population, this.network, kk).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); ActivityFacilities facilities = this.getFacilities(); if (facilities != null) { new FacilitiesWriter((ActivityFacilitiesImpl) facilities).write(this.controlerIO.getOutputFilename("output_facilities.xml.gz")); } if (((NetworkFactoryImpl) this.network.getFactory()).isTimeVariant()) { new NetworkChangeEventsWriter().write(this.controlerIO.getOutputFilename("output_change_events.xml.gz"), ((NetworkImpl) this.network).getNetworkChangeEvents()); } if (this.config.scenario().isUseHouseholds()) { new HouseholdsWriterV10(this.scenarioData.getHouseholds()).writeFile(this.controlerIO.getOutputFilename(FILENAME_HOUSEHOLDS)); } if (this.config.scenario().isUseLanes()) { new LaneDefinitionsWriter20(this.scenarioData.getScenarioElement(LaneDefinitions20.class)).write(this.controlerIO.getOutputFilename(FILENAME_LANES)); } if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); } } Code Sample 2: public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
11
Code Sample 1: public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } } Code Sample 2: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
00
Code Sample 1: public void addUser(String username, String password, String filename) { String data = ""; try { open(filename); MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); data = username + " " + encPasswd + "\r\n"; } try { long length = file.length(); file.seek(length); file.write(data.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } close(); } catch (NoSuchAlgorithmException ex) { } } Code Sample 2: public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url = l.getResource("weka/core/parser/JFlex/skeleton.default"); if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
11
Code Sample 1: public static void copyFile(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: public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).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(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
00
Code Sample 1: protected Source resolveRepositoryURI(String path) throws TransformerException { Source resolvedSource = null; try { if (path != null) { URL url = new URL(path); InputStream in = url.openStream(); if (in != null) { resolvedSource = new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible."); } } catch (MalformedURLException mfue) { throw new TransformerException("Error accessing resource using servlet context: " + path, mfue); } catch (IOException ioe) { throw new TransformerException("Unable to access resource at: " + path, ioe); } return resolvedSource; } Code Sample 2: private Map getBlackHoleData() throws Exception { File dataFile = new File(Kit.getDataDir() + BLACK_HOLE); if (dataFile.exists() && daysOld(dataFile) < 1) { return getStoredData(dataFile); } InputStream stream = null; try { String bh_url = "http://www.critique.org/users/critters/blackholes/sightdata.html"; URL url = new URL(bh_url); stream = url.openStream(); } catch (IOException e) { return getStoredData(dataFile); } BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuffer data = new StringBuffer(); String line; while ((line = br.readLine()) != null) { data.append(line); } br.close(); Pattern p = Pattern.compile(regexp); Matcher m = p.matcher(data); Map map = new THashMap(); while (m.find()) { map.put(m.group(1).trim(), new ReplyTimeDatum(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)), 0, Integer.parseInt(m.group(2)))); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFile)); oos.writeObject(map); oos.close(); return map; }
11
Code Sample 1: private synchronized void ensureParsed() throws IOException, BadIMSCPException { if (cp != null) return; if (on_disk == null) { on_disk = createTemporaryFile(); OutputStream to_disk = new FileOutputStream(on_disk); IOUtils.copy(in.getInputStream(), to_disk); to_disk.close(); } try { ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser(); parser.parse(on_disk); cp = parser.getPackage(); } catch (BadParseException x) { throw new BadIMSCPException("Cannot parse content package", x); } } Code Sample 2: public static boolean copyFile(String sourceFileName, String destFileName) { FileChannel ic = null; FileChannel oc = null; try { ic = new FileInputStream(sourceFileName).getChannel(); oc = new FileOutputStream(destFileName).getChannel(); ic.transferTo(0, ic.size(), oc); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { ic.close(); } catch (IOException e) { e.printStackTrace(); } try { oc.close(); } catch (IOException e) { e.printStackTrace(); } } return false; }
11
Code Sample 1: private void CopyTo(File dest) throws IOException { FileReader in = null; FileWriter out = null; int c; try { in = new FileReader(image); out = new FileWriter(dest); while ((c = in.read()) != -1) out.write(c); } finally { if (in != null) try { in.close(); } catch (Exception e) { } if (out != null) try { out.close(); } catch (Exception e) { } } } Code Sample 2: protected void sendDoc(File indir, File outdir, File orig, Document doc, ServiceEndpoint ep) { ep.setMethod("simpleDocumentTransfer"); Document response = null; try { response = protocolHandler.sendMessage(ep, doc); } catch (TransportException e) { logger.warn("Message was not accepted, will try again later"); return; } String serial = String.valueOf(System.currentTimeMillis()); File origCopy = new File(outdir, orig.getName() + "." + serial); File respDrop = new File(outdir, orig.getName() + "." + serial + ".resp"); FileOutputStream respos = null; try { respos = new FileOutputStream(respDrop); serializeDocument(respos, response); } catch (IOException e) { logger.warn("Failed to dump response"); return; } finally { try { respos.close(); } catch (IOException ignored) { } } FileInputStream in = null; FileOutputStream out = null; byte[] buffer = new byte[2048]; try { in = new FileInputStream(orig); out = new FileOutputStream(origCopy); int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy original"); return; } finally { try { in.close(); out.close(); } catch (IOException ignored) { } } orig.delete(); logger.info("File processed: " + orig.getName()); }
11
Code Sample 1: public static void zip(File srcDir, File destFile, FileFilter filter) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(destFile)); Collection<File> files = FileUtils.listFiles(srcDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (File f : files) { if (filter == null || filter.accept(f)) { FileInputStream in = FileUtils.openInputStream(f); out.putNextEntry(new ZipEntry(Util.relativePath(srcDir, f).replace('\\', '/'))); IOUtils.copyLarge(in, out); out.closeEntry(); IOUtils.closeQuietly(in); } } IOUtils.closeQuietly(out); } catch (Throwable t) { throw new IOException("Failed to create zip file", t); } finally { if (out != null) { out.flush(); IOUtils.closeQuietly(out); } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: private void readAnnotations() throws IOException { final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); try { String line = null; while ((line = in.readLine()) != null) { lineNumber++; if (line.startsWith("ANNOTATE")) { readAnnotationBlock(in); } } } catch (IOException e) { throw e; } finally { in.close(); } } Code Sample 2: public static boolean downloadFile(String url, String destination) throws Exception { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; byte BUFFER[] = new byte[100]; java.net.URL fileurl; URLConnection conn; fileurl = new java.net.URL(url); conn = fileurl.openConnection(); long fullsize = conn.getContentLength(); long onepercent = fullsize / 100; MessageFrame.setTotalDownloadSize(fullsize); bi = new BufferedInputStream(conn.getInputStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int read = 0; int sum = 0; long i = 0; while ((read = bi.read(BUFFER)) != -1) { bo.write(BUFFER, 0, read); sum += read; i += read; if (i > onepercent) { i = 0; MessageFrame.setDownloadProgress(sum); } } bi.close(); bo.close(); MessageFrame.setDownloadProgress(fullsize); return true; }