label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static void forEachLine(final URL url, final LineListener lit, final String encoding) { try { ReaderUtils.forEachLine(url.openStream(), lit); } catch (final IOException ioe) { lit.exception(ioe); } } Code Sample 2: static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } }
00
Code Sample 1: public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } }
00
Code Sample 1: public static String MD5ToString(String md5) { String hashword = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(md5.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { String urltext = "http://www.vogella.de"; URL url = new URL(urltext); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public static boolean verifyPassword(String digest, String password) { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } try { MessageDigest sha = MessageDigest.getInstance(alg); if (sha == null) { return false; } byte[][] hs = split(Base64.decode(digest), size); byte[] hash = hs[0]; byte[] salt = hs[1]; sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); return MessageDigest.isEqual(hash, pwhash); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } } Code Sample 2: public String getDigest(String s) throws Exception { MessageDigest md = MessageDigest.getInstance(hashName); md.update(s.getBytes()); byte[] dig = md.digest(); return Base16.toHexString(dig); }
00
Code Sample 1: protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); } Code Sample 2: public static boolean getFile(String s, String name) { try { File f = new File("D:\\buttons\\data\\sounds\\" + name); URL url = new URL(s); URLConnection conn = url.openConnection(); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); int ch; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f)); while ((ch = bis.read()) != -1) { bos.write(ch); } System.out.println("wrote audio url: " + s + " \nto file " + f); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); } Code Sample 2: public TempFileBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".bin"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
11
Code Sample 1: private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } } Code Sample 2: private void doTask() { try { log("\n\n\n\n\n\n\n\n\n"); log(" ================================================="); log(" = Starting PSCafePOS ="); log(" ================================================="); log(" = An open source point of sale system ="); log(" = for educational organizations. ="); log(" ================================================="); log(" = General Information ="); log(" = http://pscafe.sourceforge.net ="); log(" = Free Product Support ="); log(" = http://www.sourceforge.net/projects/pscafe ="); log(" ================================================="); log(" = License Overview ="); log(" ================================================="); log(" = PSCafePOS is a POS System for Schools ="); log(" = Copyright (C) 2007 Charles Syperski ="); log(" = ="); log(" = This program is free software; you can ="); log(" = redistribute it and/or modify it under the ="); log(" = terms of the GNU General Public License as ="); log(" = published by the Free Software Foundation; ="); log(" = either version 2 of the License, or any later ="); log(" = version. ="); log(" = ="); log(" = This program is distributed in the hope that ="); log(" = it will be useful, but WITHOUT ANY WARRANTY; ="); log(" = without even the implied warranty of ="); log(" = MERCHANTABILITY or FITNESS FOR A PARTICULAR ="); log(" = PURPOSE. ="); log(" = ="); log(" = See the GNU General Public License for more ="); log(" = details. ="); log(" = ="); log(" = You should have received a copy of the GNU ="); log(" = General Public License along with this ="); log(" = program; if not, write to the ="); log(" = ="); log(" = Free Software Foundation, Inc. ="); log(" = 59 Temple Place, Suite 330 ="); log(" = Boston, MA 02111-1307 USA ="); log(" ================================================="); log(" = If you have any questions of comments please ="); log(" = let us know at http://pscafe.sourceforge.net ="); log(" ================================================="); pause(); File settings; if (blAltSettings) { System.out.println("\n + Alternative path specified at run time:"); System.out.println(" Path: " + strAltPath); settings = new File(strAltPath); } else { settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Checking for existance of settings..."); boolean blGo = false; if (settings.exists() && settings.canRead()) { log("[OK]"); blGo = true; if (forceConfig) { System.out.print("\n + Running Config Wizard (at user request)..."); Process pp = Runtime.getRuntime().exec("java -cp . PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = pp.getErrorStream(); InputStream stdin = pp.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); pp.waitFor(); } } else { log("[FAILED]"); settings = new File("etc" + File.separatorChar + "settings.dbp.firstrun"); System.out.print("\n + Checking if this is the first run... "); if (settings.exists() && settings.canRead()) { log("[FOUND]"); File toFile = new File("etc" + File.separatorChar + "settings.dbp"); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(settings); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } if (toFile.exists() && toFile.canRead()) { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Running Settings Wizard... "); try { Process p = Runtime.getRuntime().exec("java PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = p.getErrorStream(); InputStream stdin = p.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); p.waitFor(); log("[OK]"); if (p.exitValue() == 0) blGo = true; } catch (InterruptedException i) { System.err.println(i.getMessage()); } } catch (Exception ex) { System.err.println(ex.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } else { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); DBSettingsWriter writ = new DBSettingsWriter(); writ.writeFile(new DBSettings(), settings); blGo = true; } } if (blGo) { String cp = "."; try { File classpath = new File("lib"); File[] subFiles = classpath.listFiles(); for (int i = 0; i < subFiles.length; i++) { if (subFiles[i].isFile()) { cp += File.pathSeparatorChar + "lib" + File.separatorChar + subFiles[i].getName() + ""; } } } catch (Exception e) { System.err.println(e.getMessage()); } try { boolean blExecutePOS = false; System.out.print("\n + Checking runtime settings... "); DBSettings info = null; if (settings == null) settings = new File("etc" + File.separatorChar + "settings.dbp"); if (settings.exists() && settings.canRead()) { DBSettingsWriter writ = new DBSettingsWriter(); info = (DBSettings) writ.loadSettingsDB(settings); if (info != null) { blExecutePOS = true; } } if (blExecutePOS) { log("[OK]"); String strSSL = ""; String strSSLDebug = ""; if (info != null) { debug = info.get(DBSettings.MAIN_DEBUG).compareTo("1") == 0; if (debug) log(" * Debug Mode is ON"); else log(" * Debug Mode is OFF"); if (info.get(DBSettings.POS_SSLENABLED).compareTo("1") == 0) { strSSL = "-Djavax.net.ssl.keyStore=" + info.get(DBSettings.POS_SSLKEYSTORE) + " -Djavax.net.ssl.keyStorePassword=pscafe -Djavax.net.ssl.trustStore=" + info.get(DBSettings.POS_SSLTRUSTSTORE) + " -Djavax.net.ssl.trustStorePassword=pscafe"; log(" * Using SSL"); debug(" " + strSSL); if (info.get(DBSettings.POS_SSLDEBUG).compareTo("1") == 0) { strSSLDebug = "-Djavax.net.debug=all"; log(" * SSL Debugging enabled"); debug(" " + strSSLDebug); } } } String strPOSRun = "java -cp " + cp + " " + strSSL + " " + strSSLDebug + " POSDriver " + settings.getPath(); debug(strPOSRun); System.out.print("\n + Running PSCafePOS... "); Process pr = Runtime.getRuntime().exec(strPOSRun); System.out.print("[OK]\n\n"); InputStream stderr = pr.getErrorStream(); InputStream stdin = pr.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); InputStreamReader isre = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); BufferedReader bre = new BufferedReader(isre); String line = null; String lineError = null; log(" ================================================="); log(" = Output from PSCafePOS System ="); log(" ================================================="); while ((line = br.readLine()) != null || (lineError = bre.readLine()) != null) { if (line != null) System.out.println(" [PSCafePOS]" + line); if (lineError != null) System.out.println(" [ERR]" + lineError); } pr.waitFor(); log(" ================================================="); log(" = End output from PSCafePOS System ="); log(" = PSCafePOS has exited ="); log(" ================================================="); } else { log("[Failed]"); } } catch (Exception i) { log(i.getMessage()); i.printStackTrace(); } } } catch (Exception e) { log(e.getMessage()); } }
11
Code Sample 1: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } Code Sample 2: public static String crypt(String password, String salt) { if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } int saltEnd = salt.indexOf('$'); if (saltEnd != -1) { salt = salt.substring(0, saltEnd); } if (salt.length() > 8) { salt = salt.substring(0, 8); } MessageDigest md5_1, md5_2; try { md5_1 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } md5_1.update(password.getBytes()); md5_1.update(magic.getBytes()); md5_1.update(salt.getBytes()); try { md5_2 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } md5_2.update(password.getBytes()); md5_2.update(salt.getBytes()); md5_2.update(password.getBytes()); byte[] md5_2_digest = md5_2.digest(); int md5Size = md5_2_digest.length; int pwLength = password.length(); for (int i = pwLength; i > 0; i -= md5Size) { md5_1.update(md5_2_digest, 0, i > md5Size ? md5Size : i); } md5_2.reset(); byte[] pwBytes = password.getBytes(); for (int i = pwLength; i > 0; i >>= 1) { if ((i & 1) == 1) { md5_1.update((byte) 0); } else { md5_1.update(pwBytes[0]); } } StringBuffer output = new StringBuffer(magic); output.append(salt); output.append("$"); byte[] md5_1_digest = md5_1.digest(); byte[] saltBytes = salt.getBytes(); for (int i = 0; i < 1000; i++) { md5_2.reset(); if ((i & 1) == 1) { md5_2.update(pwBytes); } else { md5_2.update(md5_1_digest); } if (i % 3 != 0) { md5_2.update(saltBytes); } if (i % 7 != 0) { md5_2.update(pwBytes); } if ((i & 1) != 0) { md5_2.update(md5_1_digest); } else { md5_2.update(pwBytes); } md5_1_digest = md5_2.digest(); } int value; value = ((md5_1_digest[0] & 0xff) << 16) | ((md5_1_digest[6] & 0xff) << 8) | (md5_1_digest[12] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[1] & 0xff) << 16) | ((md5_1_digest[7] & 0xff) << 8) | (md5_1_digest[13] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[2] & 0xff) << 16) | ((md5_1_digest[8] & 0xff) << 8) | (md5_1_digest[14] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[3] & 0xff) << 16) | ((md5_1_digest[9] & 0xff) << 8) | (md5_1_digest[15] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[4] & 0xff) << 16) | ((md5_1_digest[10] & 0xff) << 8) | (md5_1_digest[5] & 0xff); output.append(cryptTo64(value, 4)); value = md5_1_digest[11] & 0xff; output.append(cryptTo64(value, 2)); md5_1 = null; md5_2 = null; md5_1_digest = null; md5_2_digest = null; pwBytes = null; saltBytes = null; password = salt = null; return output.toString(); }
11
Code Sample 1: public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); } 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 void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } } Code Sample 2: public void xtest12() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf"); InputStream page1 = manager.cut(pdf, 36, 36); OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
11
Code Sample 1: public static void unzip(File zipInFile, File outputDir) throws Exception { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(zipInFile); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipInFile)); ZipEntry entry = (ZipEntry) zipInputStream.getNextEntry(); File curOutDir = outputDir; while (entry != null) { if (entry.isDirectory()) { curOutDir = new File(curOutDir, entry.getName()); curOutDir.mkdirs(); continue; } File outFile = new File(curOutDir, entry.getName()); File tempDir = outFile.getParentFile(); if (!tempDir.exists()) tempDir.mkdirs(); outFile.createNewFile(); BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream(outFile)); int n; byte[] buf = new byte[1024]; while ((n = zipInputStream.read(buf, 0, 1024)) > -1) outstream.write(buf, 0, n); outstream.flush(); outstream.close(); zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); } zipInputStream.close(); zipFile.close(); } Code Sample 2: public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; }
00
Code Sample 1: protected void initDefaultRolesFile() { String webConfigPath = System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3"); File mappingFile = new File(webConfigPath + "roles.json"); if (!mappingFile.isAbsolute()) mappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), mappingFile.getPath()); if (mappingFile.exists()) return; log.info("Init default Role Mapping file! mappingFile:" + mappingFile); if (mappingFile.getParentFile().mkdirs()) log.info("M-WRITE dir:" + mappingFile.getParent()); FileChannel fos = null; InputStream is = null; try { URL url = getClass().getResource("/META-INF/roles-default.json"); log.info("Use default Mapping File content of url:" + url); is = url.openStream(); ReadableByteChannel inCh = Channels.newChannel(is); fos = new FileOutputStream(mappingFile).getChannel(); int pos = 0; while (is.available() > 0) pos += fos.transferFrom(inCh, pos, is.available()); } catch (Exception e) { log.error("Roles file doesn't exist and the default can't be created!", e); } finally { close(is); close(fos); } } Code Sample 2: private static void addFromResource(String resource, OutputStream out) { URL url = OpenOfficeDocumentCreator.class.getResource(resource); try { InputStream in = url.openStream(); byte[] buffer = new byte[256]; synchronized (in) { synchronized (out) { while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private SystemProperties() { Properties p = new Properties(); ClassLoader classLoader = getClass().getClassLoader(); try { URL url = classLoader.getResource("system.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } try { URL url = classLoader.getResource("system-ext.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } boolean systemPropertiesLoad = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_LOAD), true); boolean systemPropertiesFinal = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_FINAL), true); if (systemPropertiesLoad) { Enumeration enu = p.propertyNames(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); if (systemPropertiesFinal || Validator.isNull(System.getProperty(key))) { System.setProperty(key, (String) p.get(key)); } } } PropertiesUtil.fromProperties(p, _props); } Code Sample 2: public void openFtpConnection(String workingDirectory) throws RQLException { try { ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(user, password); ftpClient.changeWorkingDirectory(workingDirectory); } catch (IOException ioex) { throw new RQLException("FTP client could not be created. Please check attributes given in constructor.", ioex); } }
00
Code Sample 1: public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException { if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength); if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'"); HashCash result = new HashCash(); MessageDigest md = MessageDigest.getInstance("SHA1"); result.myResource = resource; result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions); result.myDate = date; result.myVersion = version; String prefix; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); switch(version) { case 0: prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); md.reset(); md.update(result.myToken.getBytes()); result.myValue = numberOfLeadingZeros(md.digest()); break; case 1: result.myValue = value; prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); break; default: throw new IllegalArgumentException("Only supported versions are 0 and 1"); } return result; } Code Sample 2: public static boolean installMetricsCfg(Db db, String xmlFileName) throws Exception { String xmlText = FileHelper.asString(xmlFileName); Bundle bundle = new Bundle(); loadMetricsCfg(bundle, xmlFileName, xmlText); try { db.begin(); PreparedStatement psExists = db.prepareStatement("SELECT e_bundle_id, xml_decl_path, xml_text FROM sdw.e_bundle WHERE xml_decl_path = ?;"); psExists.setString(1, xmlFileName); ResultSet rsExists = db.executeQuery(psExists); if (rsExists.next()) { db.rollback(); return false; } PreparedStatement psId = db.prepareStatement("SELECT currval('sdw.e_bundle_serial');"); PreparedStatement psAdd = db.prepareStatement("INSERT INTO sdw.e_bundle (xml_decl_path, xml_text, sdw_major_version, sdw_minor_version, file_major_version, file_minor_version) VALUES (?, ?, ?, ?, ?, ?);"); psAdd.setString(1, xmlFileName); psAdd.setString(2, xmlText); FileInformation fi = bundle.getSingleFileInformation(); if (!xmlFileName.equals(fi.filename)) throw new IllegalStateException("FileInformation bad for " + xmlFileName); psAdd.setInt(3, Globals.SDW_MAJOR_VER); psAdd.setInt(4, Globals.SDW_MINOR_VER); psAdd.setInt(5, fi.majorVer); psAdd.setInt(6, fi.minorVer); if (1 != db.executeUpdate(psAdd)) { throw new IllegalStateException("Could not add " + xmlFileName); } int bundleId = DbHelper.getIntKey(psId); PreparedStatement psGroupId = db.prepareStatement("SELECT currval('sdw.e_metric_group_serial');"); PreparedStatement psAddGroup = db.prepareStatement("INSERT INTO sdw.e_metric_group (bundle_id, metric_group_name) VALUES (?, ?);"); psAddGroup.setInt(1, bundleId); PreparedStatement psMetricId = db.prepareStatement("SELECT currval('sdw.e_metric_name_serial');"); PreparedStatement psAddMetric = db.prepareStatement("INSERT INTO sdw.e_metric_name (bundle_id, metric_name) VALUES (?, ?);"); psAddMetric.setInt(1, bundleId); PreparedStatement psAddGroup2Metric = db.prepareStatement("INSERT INTO sdw.e_metric_groups (metric_name_id, metric_group_id) VALUES (?, ?);"); Iterator<MetricGroup> i = bundle.getAllMetricGroups(); while (i.hasNext()) { MetricGroup grp = i.next(); psAddGroup.setString(2, grp.groupName); if (1 != db.executeUpdate(psAddGroup)) throw new IllegalStateException("Could not add group " + grp.groupName + " from " + xmlFileName); int groupId = DbHelper.getIntKey(psGroupId); psAddGroup2Metric.setInt(2, groupId); Iterator<String> j = grp.getAllMetricNames(); while (j.hasNext()) { String metricName = j.next(); psAddMetric.setString(2, metricName); if (1 != db.executeUpdate(psAddMetric)) throw new IllegalStateException("Could not add " + metricName + " from " + xmlFileName); int metricId = DbHelper.getIntKey(psMetricId); psAddGroup2Metric.setInt(1, metricId); if (1 != db.executeUpdate(psAddGroup2Metric)) throw new IllegalStateException("Could not add group " + grp.groupName + " -> " + metricName + " from " + xmlFileName); } } return true; } catch (Exception e) { db.rollback(); throw e; } finally { db.commitUnless(); } }
11
Code Sample 1: private static void salvarArtista(Artista artista) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into artista VALUES (?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, artista.getNumeroInscricao()); ps.setString(2, artista.getNome()); ps.setBoolean(3, artista.isSexo()); ps.setString(4, artista.getEmail()); ps.setString(5, artista.getObs()); ps.setString(6, artista.getTelefone()); ps.setNull(7, Types.INTEGER); ps.executeUpdate(); salvarEndereco(conn, ps, artista); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: public static String MD5(String text) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return text; } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return text; } } Code Sample 2: private String generateUniqueIdMD5(String workgroupIdString, String runIdString) { String passwordUnhashed = workgroupIdString + "-" + runIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(passwordUnhashed.getBytes(), 0, passwordUnhashed.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; }
11
Code Sample 1: HTTPValuePatternComponent(final String url, final long seed) throws IOException { seedRandom = new Random(seed); random = new ThreadLocal<Random>(); final ArrayList<String> lineList = new ArrayList<String>(100); final URL parsedURL = new URL(url); final HttpURLConnection urlConnection = (HttpURLConnection) parsedURL.openConnection(); final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); try { while (true) { final String line = reader.readLine(); if (line == null) { break; } lineList.add(line); } } finally { reader.close(); } if (lineList.isEmpty()) { throw new IOException(ERR_VALUE_PATTERN_COMPONENT_EMPTY_FILE.get()); } lines = new String[lineList.size()]; lineList.toArray(lines); } Code Sample 2: @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ImagesService imgService = ImagesServiceFactory.getImagesService(); InputStream stream = request.getInputStream(); ArrayList<Byte> bytes = new ArrayList<Byte>(); int b = 0; while ((b = stream.read()) != -1) { bytes.add((byte) b); } byte img[] = new byte[bytes.size()]; for (int i = 0; i < bytes.size(); i++) { img[i] = bytes.get(i); } BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); String urlBlobstore = blobstoreService.createUploadUrl("/blobstore-servlet?action=upload"); URL url = new URL("http://localhost:8888" + urlBlobstore); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=29772313"); OutputStream out = connection.getOutputStream(); out.write(img); out.flush(); out.close(); System.out.println(connection.getResponseCode()); System.out.println(connection.getResponseMessage()); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String responseText = ""; String line; while ((line = rd.readLine()) != null) { responseText += line; } out.close(); rd.close(); response.sendRedirect("/blobstore-servlet?action=getPhoto&" + responseText); }
00
Code Sample 1: private void addIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst = null; try { conn = getConnection(); pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst.setInt(1, id); pst.setString(2, ingBean.getName()); pst.setDouble(3, ingBean.getAmount()); pst.setInt(4, ingBean.getType()); pst.setInt(5, ingBean.getShopFlag()); pst.executeUpdate(); } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst != null) pst.close(); pst = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } } Code Sample 2: private ExamModel(URL urlQuestions) throws IOException, DataCoherencyException { BufferedReader in = new BufferedReader(new InputStreamReader(urlQuestions.openStream())); String line; questions = new ArrayList<Question>(); questionsMap = new HashMap<String, Question>(); in = new BufferedReader(new InputStreamReader(urlQuestions.openStream(), "UTF-8")); int questionNumber = 0; Question question; String questText = ""; String hash = ""; int lookingFor = ExamModel.READING_HASH; while ((line = in.readLine()) != null) { switch(lookingFor) { case ExamModel.READING_HASH: if (line.length() == 0 || line.trim().length() == 0) continue; hash = line; questionNumber++; lookingFor = ExamModel.READING_QUESTION; break; case ExamModel.READING_QUESTION: if (line.equals("--")) { question = new Question(questionNumber, hash, questText); questions.add(question); questionsMap.put(question.getHash(), question); questText = ""; hash = null; lookingFor = ExamModel.READING_HASH; } else { questText = questText.concat(line + Constants.nl); } break; default: throw new DataCoherencyException("Neočekávaný konec souboru!"); } } questions.trimToSize(); in.close(); }
00
Code Sample 1: private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri, ClientConnectionManager connectionManager) { InputStream contentInput = null; if (connectionManager == null) { try { URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); conn.connect(); contentInput = conn.getInputStream(); } catch (Exception e) { Log.w(TAG, "Request failed: " + uri); e.printStackTrace(); return null; } } else { final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS); HttpUriRequest request = new HttpGet(uri); HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { contentInput = entity.getContent(); } } catch (Exception e) { Log.w(TAG, "Request failed: " + request.getURI()); return null; } } if (contentInput != null) { return new BufferedInputStream(contentInput, 4096); } else { return null; } } Code Sample 2: public LOCKSSDaemonStatusTableTO getDataFromDaemonStatusTable() throws HttpResponseException { LOCKSSDaemonStatusTableXmlStreamParser ldstxp = null; LOCKSSDaemonStatusTableTO ldstTO = null; HttpEntity entity = null; HttpGet httpget = null; xstream.setMode(XStream.NO_REFERENCES); xstream.alias("HttpClientDAO", HttpClientDAO.class); try { httpget = new HttpGet(dataUrl); logger.log(Level.INFO, "executing request {0}", httpget.getURI()); HttpResponse resp = httpClient.execute(httpget); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.log(Level.WARNING, "response to the request is not OK: skip this IP: status code={0}", statusCode); httpget.abort(); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); return ldstTO; } entity = resp.getEntity(); InputStream is = entity.getContent(); ldstxp = new LOCKSSDaemonStatusTableXmlStreamParser(); ldstxp.read(new BufferedInputStream(is)); ldstTO = ldstxp.getLOCKSSDaemonStatusTableTO(); ldstTO.setIpAddress(this.ip); logger.log(Level.INFO, "After parsing [{0}] table", this.tableId); logger.log(Level.FINEST, "After parsing {0}: contents of ldstTO:\n{1}", new Object[] { this.tableId, ldstTO }); if (ldstTO.hasIncompleteRows) { logger.log(Level.WARNING, "!!!!!!!!! incomplete rows are found for {0}", tableId); if (ldstTO.getTableData() != null && ldstTO.getTableData().size() > 0) { logger.log(Level.FINE, "incomplete rows: table(map) data dump =[\n{0}\n]", xstream.toXML(ldstTO.getTableData())); } } else { logger.log(Level.INFO, "All rows are complete for {0}", tableId); } } catch (ConnectTimeoutException ce) { logger.log(Level.WARNING, "ConnectTimeoutException occurred", ce); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (SocketTimeoutException se) { logger.log(Level.WARNING, "SocketTimeoutException occurred", se); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (ClientProtocolException pe) { logger.log(Level.SEVERE, "The protocol was not http; https is suspected", pe); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); ldstTO.setHttpProtocol(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (IOException ex) { logger.log(Level.SEVERE, "IO exception occurs", ex); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (IOException ex) { logger.log(Level.SEVERE, "io exception when entity was to be" + "consumed", ex); } } } return ldstTO; }
00
Code Sample 1: private void putFile(String location, String file) throws Exception { System.out.println("Put file to " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true); RDFFormat dataFormat = RDFFormat.forFileName(file, RDFFormat.RDFXML); conn.setRequestProperty("Content-Type", dataFormat.getDefaultMIMEType()); InputStream dataStream = ProtocolTest.class.getResourceAsStream(file); try { OutputStream connOut = conn.getOutputStream(); try { IOUtil.transfer(dataStream, connOut); } finally { connOut.close(); } } finally { dataStream.close(); } conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } } Code Sample 2: private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
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: @Test public void testWriteAndReadBiggerUnbuffered() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwriteb.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwriteb.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int b = in.read(); while (b != -1) { tmp.write(b); b = in.read(); } byte[] buffer = tmp.toByteArray(); in.close(); assertEquals(body.length(), buffer.length); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
11
Code Sample 1: @Override public void send() { BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result.append(str); } } catch (ConnectException ce) { logger.error("MockupExecutableCommand excute fail: " + ce.getMessage()); } catch (Exception e) { logger.error("MockupExecutableCommand excute fail: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } } Code Sample 2: public void testBasic() { CameraInfo ci = C328rCameraInfo.getInstance(); assertNotNull(ci); assertNotNull(ci.getCapabilities()); assertFalse(ci.getCapabilities().isEmpty()); System.out.println(ci.getUrl()); URL url = ci.getUrl(); try { URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: private void generateSchema() { ConsoleOutputWindow console = DefaultXPontusWindowImpl.getInstance().getConsole(); MessagesWindowDockable mconsole = (MessagesWindowDockable) console.getDockableById(MessagesWindowDockable.DOCKABLE_ID); ByteArrayOutputStream bao = new ByteArrayOutputStream(); IDocumentContainer container = (IDocumentContainer) DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentDockable(); try { SchemaGenerationModel model = view.getModel(); boolean isValid = transformationIsValid(model); if (!isValid) { return; } DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Generating schema..."); view.setVisible(false); InputFormat inFormat = null; OutputFormat of = null; if (model.getInputType().equalsIgnoreCase("RELAX NG Grammar")) { inFormat = new SAXParseInputFormat(); } else if (model.getInputType().equalsIgnoreCase("RELAX NG Compact Grammar")) { inFormat = new CompactParseInputFormat(); } else if (model.getInputType().equalsIgnoreCase("DTD")) { inFormat = new DtdInputFormat(); } else if (model.getInputType().equalsIgnoreCase("XML")) { inFormat = new XmlInputFormat(); } if (model.getOutputType().equalsIgnoreCase("DTD")) { of = new DtdOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("Relax NG Grammar")) { of = new RngOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("XML Schema")) { of = new XsdOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("Relax NG Compact Grammar")) { of = new RncOutputFormat(); } ErrorHandlerImpl eh = new ErrorHandlerImpl(bao); SchemaCollection sc = null; if (!view.getModel().isUseExternalDocument()) { JTextComponent jtc = DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentEditor(); if (jtc == null) { XPontusComponentsUtils.showErrorMessage("No document opened!!!"); DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!"); return; } String suffixe = model.getOutputType().toLowerCase(); File tmp = File.createTempFile("schemageneratorhandler", +System.currentTimeMillis() + "." + suffixe); OutputStream m_outputStream = new FileOutputStream(tmp); CharsetDetector detector = new CharsetDetector(); detector.setText(jtc.getText().getBytes()); Writer m_writer = new OutputStreamWriter(m_outputStream, "UTF-8"); IOUtils.copy(detector.detect().getReader(), m_writer); IOUtils.closeQuietly(m_writer); try { sc = inFormat.load(UriOrFile.toUri(tmp.getAbsolutePath()), new String[0], model.getOutputType().toLowerCase(), eh); } catch (Exception ife) { ife.printStackTrace(); StrBuilder stb = new StrBuilder(); stb.append("\nError loading input document!\n"); stb.append("Maybe the input type is invalid?\n"); stb.append("Please check again the input type list or trying validating your document\n"); throw new Exception(stb.toString()); } tmp.deleteOnExit(); } else { try { sc = inFormat.load(UriOrFile.toUri(view.getModel().getInputURI()), new String[0], model.getOutputType().toLowerCase(), eh); } catch (Exception ife) { StrBuilder stb = new StrBuilder(); stb.append("\nError loading input document!\n"); stb.append("Maybe the input type is invalid?\n"); stb.append("Please check again the input type list or trying validating your document\n"); throw new Exception(stb.toString()); } } OutputDirectory od = new LocalOutputDirectory(sc.getMainUri(), new File(view.getModel().getOutputURI()), model.getOutputType().toLowerCase(), DEFAULT_OUTPUT_ENCODING, DEFAULT_LINE_LENGTH, DEFAULT_INDENT); of.output(sc, od, new String[0], model.getInputType().toLowerCase(), eh); mconsole.println("Schema generated sucessfully!"); DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Schema generated sucessfully!"); if (model.isOpenInEditor()) { XPontusComponentsUtils.showWarningMessage("The document will NOT be opened in the editor sorry for that!\n You need to open it yourself."); } } catch (Exception ex) { DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!"); StringWriter sw = new StringWriter(); PrintWriter ps = new PrintWriter(sw); ex.printStackTrace(ps); StrBuilder sb = new StrBuilder(); sb.append("Error generating schema"); sb.appendNewLine(); sb.append(new String(bao.toByteArray())); sb.appendNewLine(); if (ex instanceof SAXParseException) { SAXParseException spe = (SAXParseException) ex; sb.append("Error around line " + spe.getLineNumber()); sb.append(", column " + spe.getColumnNumber()); sb.appendNewLine(); } sb.append(sw.toString()); mconsole.println(sb.toString(), OutputDockable.RED_STYLE); logger.error(sb.toString()); try { ps.flush(); ps.close(); sw.flush(); sw.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } } finally { console.setFocus(MessagesWindowDockable.DOCKABLE_ID); Toolkit.getDefaultToolkit().beep(); } } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: public Source resolve(String href, String base) throws TransformerException { if (href.endsWith(".txt")) { try { URL url = new URL(new URL(base), href); java.io.InputStream in = url.openConnection().getInputStream(); java.io.InputStreamReader reader = new java.io.InputStreamReader(in, "iso-8859-1"); StringBuffer sb = new StringBuffer(); while (true) { int c = reader.read(); if (c < 0) break; sb.append((char) c); } com.icl.saxon.expr.TextFragmentValue tree = new com.icl.saxon.expr.TextFragmentValue(sb.toString(), url.toString(), (com.icl.saxon.Controller) transformer); return tree.getFirst(); } catch (Exception err) { throw new TransformerException(err); } } else { return null; } } Code Sample 2: @Test public final void testImportODScontentXml() throws Exception { URL url = ODSTableImporterTest.class.getResource("/Messages.ods_FILES/content.xml"); String systemId = url.getPath(); InputStream in = url.openStream(); ODSTableImporter b = new ODSTableImporter(); b.importODSContentXml(systemId, in, null); assertMessagesOds(b); }
00
Code Sample 1: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } } Code Sample 2: static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; Savepoint sp = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=1"; st.executeUpdate(sql); sp = conn.setSavepoint(); sql = "update user set money=money-10 where id=3"; st.executeUpdate(sql); sql = "select money from user where id=2"; rs = st.executeQuery(sql); float money = 0.0f; if (rs.next()) { money = rs.getFloat("money"); } if (money > 300) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=2"; st.executeUpdate(sql); conn.commit(); } catch (RuntimeException e) { if (conn != null && sp != null) { conn.rollback(sp); conn.commit(); } throw e; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } }
11
Code Sample 1: public static byte[] getHashedPassword(String password, byte[] randomBytes) { byte[] hashedPassword = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(randomBytes); messageDigest.update(password.getBytes("UTF-8")); hashedPassword = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hashedPassword; } Code Sample 2: public String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for(int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); }
11
Code Sample 1: public void testReadNormal() throws Exception { archiveFileManager.executeWith(new TemporaryFileExecutor() { public void execute(File temporaryFile) throws Exception { ZipArchive archive = new ZipArchive(temporaryFile.getPath()); InputStream input = archive.getInputFrom(ARCHIVE_FILE_1); if (input != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, output); assertEquals(ARCHIVE_FILE_1 + " contents not correct", ARCHIVE_FILE_1_CONTENT, output.toString()); } else { fail("cannot open " + ARCHIVE_FILE_1); } } }); } Code Sample 2: private long generateNativeInstallExe(File nativeInstallFile, String instTemplate, File instClassFile) throws IOException { InputStream reader = getClass().getResourceAsStream("/" + instTemplate); ByteArrayOutputStream content = new ByteArrayOutputStream(); String installClassVarStr = "000000000000"; byte[] buf = new byte[installClassVarStr.length()]; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassVarStr.length()); int installClassStopPos = 0; long installClassOffset = reader.available(); int position = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallExe")); reader.read(buf, 0, buf.length); position = 1; for (int n = 0; n < 3; n++) { while ((!new String(buf).equals("clname_here_")) && (!new String(buf).equals("clstart_here")) && (!new String(buf).equals("clstop_here_"))) { content.write(buf[0]); int nextb = reader.read(); position++; shiftArray(buf); buf[buf.length - 1] = (byte) nextb; } if (new String(buf).equals("clname_here_")) { VAGlobals.printDebug(" clname_here_ found at " + (position - 1)); StringBuffer clnameBuffer = new StringBuffer(64); clnameBuffer.append(instClassName_); for (int i = clnameBuffer.length() - 1; i < 64; i++) { clnameBuffer.append('.'); } byte[] clnameBytes = clnameBuffer.toString().getBytes(); for (int i = 0; i < 64; i++) { content.write(clnameBytes[i]); position++; } reader.skip(64 - buf.length); reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstart_here")) { VAGlobals.printDebug(" clstart_here found at " + (position - 1)); buf = nf.format(installClassOffset).getBytes(); for (int i = 0; i < buf.length; i++) { content.write(buf[i]); position++; } reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstop_here_")) { VAGlobals.printDebug(" clstop_here_ found at " + (position - 1)); installClassStopPos = position - 1; content.write(buf); position += 12; reader.read(buf, 0, buf.length); } } content.write(buf); buf = new byte[2048]; int read = reader.read(buf); while (read > 0) { content.write(buf, 0, read); read = reader.read(buf); } reader.close(); FileInputStream classStream = new FileInputStream(instClassFile); read = classStream.read(buf); while (read > 0) { content.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); content.close(); byte[] contentBytes = content.toByteArray(); installClassVarStr = nf.format(contentBytes.length); byte[] installClassVarBytes = installClassVarStr.getBytes(); for (int i = 0; i < installClassVarBytes.length; i++) { contentBytes[installClassStopPos + i] = installClassVarBytes[i]; } FileOutputStream out = new FileOutputStream(nativeInstallFile); out.write(contentBytes); out.close(); return installClassOffset; }
11
Code Sample 1: public JavaCodeAnalyzer(String filenameIn, String filenameOut, String lineLength) { try { File tmp = File.createTempFile("JavaCodeAnalyzer", "tmp"); BufferedReader br = new BufferedReader(new FileReader(filenameIn)); BufferedWriter out = new BufferedWriter(new FileWriter(tmp)); while (br.ready()) { out.write(br.read()); } br.close(); out.close(); jco = new JavaCodeOutput(tmp, filenameOut, lineLength); SourceCodeParser p = new JavaCCParserFactory().createParser(new FileReader(tmp), null); List statements = p.parseCompilationUnit(); ListIterator it = statements.listIterator(); eh = new ExpressionHelper(this, jco); Node n; printLog("Parsed file " + filenameIn + "\n"); while (it.hasNext()) { n = (Node) it.next(); parseObject(n); } tmp.delete(); } catch (Exception e) { System.err.println(getClass() + ": " + e); } } Code Sample 2: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
00
Code Sample 1: public void downloadFtpFile(SynchrnServerVO synchrnServerVO, String fileNm) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(synchrnServerVO.getServerIp())) { throw new RuntimeException("IP is needed. (" + synchrnServerVO.getServerIp() + ")"); } InetAddress host = InetAddress.getByName(synchrnServerVO.getServerIp()); ftpClient.connect(host, Integer.parseInt(synchrnServerVO.getServerPort())); ftpClient.login(synchrnServerVO.getFtpId(), synchrnServerVO.getFtpPassword()); ftpClient.changeWorkingDirectory(synchrnServerVO.getSynchrnLc()); File downFile = new File(EgovWebUtil.filePathBlackList(synchrnServerVO.getFilePath() + fileNm)); OutputStream outputStream = null; try { outputStream = new FileOutputStream(downFile); ftpClient.retrieveFile(fileNm, outputStream); } catch (Exception e) { System.out.println(e); } finally { if (outputStream != null) outputStream.close(); } ftpClient.logout(); } Code Sample 2: public static void loadMemcachedConfigFromURL(URL url, XMLInputFactory factory, List<MemcachedClientConfig> memcachedClientconfigs, List<MemcachedClientSocketPoolConfig> memcachedClientSocketPoolConfigs, List<MemcachedClientClusterConfig> memcachedClientClusterConfig) { MemcachedClientConfig node = null; MemcachedClientSocketPoolConfig socketnode = null; MemcachedClientClusterConfig clusternode = null; InputStream in = null; XMLEventReader r = null; try { in = url.openStream(); r = factory.createXMLEventReader(in); String servers = null; String weights = null; while (r.hasNext()) { XMLEvent event = r.nextEvent(); if (event.isStartElement()) { StartElement start = event.asStartElement(); String tag = start.getName().getLocalPart(); if (tag.equalsIgnoreCase("client")) { node = new MemcachedClientConfig(); if (start.getAttributeByName(new QName("", "name")) != null) node.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client name can't not be null!"); if (start.getAttributeByName(new QName("", "socketpool")) != null) node.setSocketPool(start.getAttributeByName(new QName("", "socketpool")).getValue()); else throw new RuntimeException("memcached client socketpool can't not be null!"); if (start.getAttributeByName(new QName("", "compressEnable")) != null) node.setCompressEnable(Boolean.parseBoolean(start.getAttributeByName(new QName("", "compressEnable")).getValue())); else node.setCompressEnable(true); if (start.getAttributeByName(new QName("", "defaultEncoding")) != null) node.setDefaultEncoding(start.getAttributeByName(new QName("", "defaultEncoding")).getValue()); else node.setDefaultEncoding("UTF-8"); continue; } if (tag.equalsIgnoreCase("errorHandler") && node != null) { event = r.peek(); if (event.isCharacters()) { node.setErrorHandler(event.asCharacters().getData()); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("socketpool")) { socketnode = new MemcachedClientSocketPoolConfig(); servers = null; weights = null; if (start.getAttributeByName(new QName("", "name")) != null) socketnode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client socketpool name can't not be null!"); if (start.getAttributeByName(new QName("", "failover")) != null) socketnode.setFailover(Boolean.parseBoolean(start.getAttributeByName(new QName("", "failover")).getValue())); if (start.getAttributeByName(new QName("", "initConn")) != null) socketnode.setInitConn(Integer.parseInt(start.getAttributeByName(new QName("", "initConn")).getValue())); if (start.getAttributeByName(new QName("", "minConn")) != null) socketnode.setMinConn(Integer.parseInt(start.getAttributeByName(new QName("", "minConn")).getValue())); if (start.getAttributeByName(new QName("", "maxConn")) != null) socketnode.setMaxConn(Integer.parseInt(start.getAttributeByName(new QName("", "maxConn")).getValue())); if (start.getAttributeByName(new QName("", "maintSleep")) != null) socketnode.setMaintSleep(Integer.parseInt(start.getAttributeByName(new QName("", "maintSleep")).getValue())); if (start.getAttributeByName(new QName("", "nagle")) != null) socketnode.setNagle(Boolean.parseBoolean(start.getAttributeByName(new QName("", "nagle")).getValue())); if (start.getAttributeByName(new QName("", "socketTO")) != null) socketnode.setSocketTo(Integer.parseInt(start.getAttributeByName(new QName("", "socketTO")).getValue())); if (start.getAttributeByName(new QName("", "maxIdle")) != null) socketnode.setMaxIdle(Integer.parseInt(start.getAttributeByName(new QName("", "maxIdle")).getValue())); if (start.getAttributeByName(new QName("", "aliveCheck")) != null) socketnode.setAliveCheck(Boolean.parseBoolean(start.getAttributeByName(new QName("", "aliveCheck")).getValue())); continue; } if (tag.equalsIgnoreCase("servers") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { servers = event.asCharacters().getData(); socketnode.setServers(servers); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("weights") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { weights = event.asCharacters().getData(); socketnode.setWeights(weights); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("cluster")) { clusternode = new MemcachedClientClusterConfig(); if (start.getAttributeByName(new QName("", "name")) != null) clusternode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached cluster name can't not be null!"); if (start.getAttributeByName(new QName("", "mode")) != null) clusternode.setMode(start.getAttributeByName(new QName("", "mode")).getValue()); continue; } if (tag.equalsIgnoreCase("memCachedClients") && clusternode != null) { event = r.peek(); if (event.isCharacters()) { String clients = event.asCharacters().getData(); if (clients != null && !clients.equals("")) { clusternode.setMemCachedClients(clients.split(",")); } r.nextEvent(); } continue; } } if (event.isEndElement()) { EndElement end = event.asEndElement(); if (node != null && end.getName().getLocalPart().equalsIgnoreCase("client")) { memcachedClientconfigs.add(node); Logger.info(new StringBuilder().append(" add memcachedClient config :").append(node.getName())); continue; } if (socketnode != null && end.getName().getLocalPart().equalsIgnoreCase("socketpool")) { memcachedClientSocketPoolConfigs.add(socketnode); Logger.info(new StringBuilder().append(" add socketpool config :").append(socketnode.getName())); continue; } if (clusternode != null && end.getName().getLocalPart().equalsIgnoreCase("cluster")) { memcachedClientClusterConfig.add(clusternode); Logger.info(new StringBuilder().append(" add cluster config :").append(clusternode.getName())); continue; } } } } catch (Exception e) { Logger.error(new StringBuilder("MemcachedManager loadConfig error !").append(" config url :").append(url.getFile()).toString()); node = null; } finally { try { if (r != null) r.close(); if (in != null) in.close(); r = null; in = null; } catch (Exception ex) { throw new RuntimeException("processConfigURL error !", ex); } } }
00
Code Sample 1: public static byte[] clearPassToUserPassword(String clearpass, HashAlg alg, byte[] salt) { if (alg == null) { throw new IllegalArgumentException("Invalid hash argorithm."); } try { MessageDigest digester = null; StringBuilder resultInText = new StringBuilder(); switch(alg) { case MD5: resultInText.append("{MD5}"); digester = MessageDigest.getInstance("MD5"); break; case SMD5: resultInText.append("{SMD5}"); digester = MessageDigest.getInstance("MD5"); break; case SHA: resultInText.append("{SHA}"); digester = MessageDigest.getInstance("SHA"); break; case SSHA: resultInText.append("{SSHA}"); digester = MessageDigest.getInstance("SHA"); break; default: break; } digester.reset(); digester.update(clearpass.getBytes(DEFAULT_ENCODING)); byte[] hash = null; if (salt != null && (alg == HashAlg.SMD5 || alg == HashAlg.SSHA)) { digester.update(salt); hash = ArrayUtils.addAll(digester.digest(), salt); } else { hash = digester.digest(); } resultInText.append(new String(Base64.encodeBase64(hash), DEFAULT_ENCODING)); return resultInText.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException uee) { log.warn("Error occurred while hashing password ", uee); return new byte[0]; } catch (java.security.NoSuchAlgorithmException nse) { log.warn("Error occurred while hashing password ", nse); return new byte[0]; } } Code Sample 2: private void addAllSpecialPages(Environment env, ZipOutputStream zipout, int progressStart, int progressLength) throws Exception, IOException { ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale); String tpl; int count = 0; int numberOfSpecialPages = 7; progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; String cssContent = wb.readRaw(virtualWiki, "StyleSheet"); addZipEntry(zipout, "css/vqwiki.css", cssContent); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; tpl = getTemplateFilledWithContent("search"); addTopicEntry(zipout, tpl, "WikiSearch", "WikiSearch.html"); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; zipout.putNextEntry(new ZipEntry("applets/export2html-applet.jar")); IOUtils.copy(new FileInputStream(ctx.getRealPath("/WEB-INF/classes/export2html/export2html-applet.jar")), zipout); zipout.closeEntry(); zipout.flush(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JarOutputStream indexjar = new JarOutputStream(bos); JarEntry jarEntry; File searchDir = new File(wb.getSearchEngine().getSearchIndexPath(virtualWiki)); String files[] = searchDir.list(); StringBuffer listOfAllFiles = new StringBuffer(); for (int i = 0; i < files.length; i++) { if (listOfAllFiles.length() > 0) { listOfAllFiles.append(","); } listOfAllFiles.append(files[i]); jarEntry = new JarEntry("lucene/index/" + files[i]); indexjar.putNextEntry(jarEntry); IOUtils.copy(new FileInputStream(new File(searchDir, files[i])), indexjar); indexjar.closeEntry(); } indexjar.flush(); indexjar.putNextEntry(new JarEntry("lucene/index.dir")); IOUtils.copy(new StringReader(listOfAllFiles.toString()), indexjar); indexjar.closeEntry(); indexjar.flush(); indexjar.close(); zipout.putNextEntry(new ZipEntry("applets/index.jar")); zipout.write(bos.toByteArray()); zipout.closeEntry(); zipout.flush(); bos.reset(); } catch (Exception e) { logger.log(Level.FINE, "Exception while adding lucene index: ", e); } progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; StringBuffer content = new StringBuffer(); content.append("<table><tr><th>" + messages.getString("common.date") + "</th><th>" + messages.getString("common.topic") + "</th><th>" + messages.getString("common.user") + "</th></tr>" + IOUtils.LINE_SEPARATOR); Collection all = null; try { Calendar cal = Calendar.getInstance(); ChangeLog cl = wb.getChangeLog(); int n = env.getIntSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS); if (n == 0) { n = 5; } all = new ArrayList(); for (int i = 0; i < n; i++) { Collection col = cl.getChanges(virtualWiki, cal.getTime()); if (col != null) { all.addAll(col); } cal.add(Calendar.DATE, -1); } } catch (Exception e) { } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); for (Iterator iter = all.iterator(); iter.hasNext(); ) { Change change = (Change) iter.next(); content.append("<tr><td class=\"recent\">" + df.format(change.getTime()) + "</td><td class=\"recent\"><a href=\"" + safename(change.getTopic()) + ".html\">" + change.getTopic() + "</a></td><td class=\"recent\">" + change.getUser() + "</td></tr>"); } content.append("</table>" + IOUtils.LINE_SEPARATOR); tpl = getTemplateFilledWithContent(null); tpl = tpl.replaceAll("@@CONTENTS@@", content.toString()); addTopicEntry(zipout, tpl, "RecentChanges", "RecentChanges.html"); logger.fine("Done adding all special topics."); }
00
Code Sample 1: private void onCheckConnection() { BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { public void run() { String baseUrl; if (_rdoSRTM3FtpUrl.getSelection()) { } else { baseUrl = _txtSRTM3HttpUrl.getText().trim(); try { final URL url = new URL(baseUrl); final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.connect(); final int response = urlConn.getResponseCode(); final String responseMessage = urlConn.getResponseMessage(); final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage }); MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message); } catch (final IOException e) { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl)); e.printStackTrace(); } } } }); } Code Sample 2: public Vector<String> getVoiceServersNames() { Vector<String> result = new Vector<String>(); boolean serverline = false; String line; String[] splitline; try { URL url = new URL(voiceaddress); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { if (serverline) { splitline = line.split(":"); result.add(splitline[0]); } if (line.startsWith("!VOICE SERVERS")) { serverline = true; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
11
Code Sample 1: private static boolean validateSshaPwd(String sSshaPwd, String sUserPwd) { boolean b = false; if (sSshaPwd != null && sUserPwd != null) { if (sSshaPwd.startsWith(SSHA_PREFIX)) { sSshaPwd = sSshaPwd.substring(SSHA_PREFIX.length()); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); 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); md.update(sUserPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); b = MessageDigest.isEqual(hash, baPwdHash); } catch (Exception exc) { exc.printStackTrace(); } } } return b; } Code Sample 2: public String encryptPassword(String clearPassword) throws NullPointerException { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new NullPointerException("NoSuchAlgorithmException: " + e.toString()); } sha.update(clearPassword.getBytes()); byte encryptedPassword[] = sha.digest(); sha = null; StringBuffer result = new StringBuffer(); for (int i = 0; i < encryptedPassword.length; i++) { result.append(Byte.toString(encryptedPassword[i])); } return (result.toString()); }
11
Code Sample 1: protected String encrypt(String text) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: private String encryptPassword(String password) throws NoSuchAlgorithmException { StringBuffer encryptedPassword = new StringBuffer(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(password.getBytes()); byte digest[] = md5.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(0xFF & digest[i]); if (hex.length() == 1) { encryptedPassword.append('0'); } encryptedPassword.append(hex); } return encryptedPassword.toString(); }
00
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 QueryResult doSearch(String searchTerm, Integer searchInReceivedItems, Integer searchInSentItems, Integer searchInSupervisedItems, Integer startRow, Integer resultCount, Boolean searchArchived, Boolean searchInItemsNeededAttentionOnly) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); QueryResult queryResult = new QueryResult(); SearchRequest request = new SearchRequest(); SearchItemsQuery query = new SearchItemsQuery(); query.setArchiveIncluded(searchArchived); log(INFO, "searchTerm=" + searchTerm); log(INFO, "search in received=" + searchInReceivedItems); log(INFO, "search in sent=" + searchInSentItems); log(INFO, "search in supervised=" + searchInSupervisedItems); List<String> filters = new ArrayList<String>(); if (searchInItemsNeededAttentionOnly == false) { if (searchInReceivedItems != null) { filters.add("ALL_RECEIVED_ITEMS"); } if (searchInSentItems != null) { filters.add("ALL_SENT_ITEMS"); } if (searchInSupervisedItems != null) { filters.add("ALL_SUPERVISED_ITEMS"); } } else { if (searchInReceivedItems != null) { filters.add("RECEIVED_ITEMS_NEEDED_ATTENTION"); } if (searchInSentItems != null) { filters.add("SENT_ITEMS_NEEDED_ATTENTION"); } } query.setFilters(filters); query.setId("1234"); query.setOwner(sessionId); query.setReferenceOnly(false); query.setSearchTerm(searchTerm); query.setUseOR(false); request.setStartRow(startRow); request.setResultCount(resultCount); request.setQuery(query); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("SearchRequest", SearchRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("SearchResponse", SearchResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/search?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); SearchResponse searchResponse = (SearchResponse) reader.fromXML(result); List<Item> items = searchResponse.getItems(); queryResult.setItems(items); queryResult.setTotal(searchResponse.getTotalResultCount()); queryResult.setStartRow(searchResponse.getStartRow()); } return queryResult; }
00
Code Sample 1: public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; } Code Sample 2: @Override public void loadTest(StoryCardModel story) { String strUrl = story.getStoryCard().getAcceptanceTestUrl(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder loader; try { URL url = new URL(strUrl); loader = factory.newDocumentBuilder(); Document document; document = loader.parse(url.openStream()); this.numPass = Integer.parseInt(((Element) document.getElementsByTagName("num-pass").item(0)).getFirstChild().getNodeValue()); this.numFail = Integer.parseInt(((Element) document.getElementsByTagName("num-fail").item(0)).getFirstChild().getNodeValue()); this.numRuns = Integer.parseInt(((Element) document.getElementsByTagName("num-runs").item(0)).getFirstChild().getNodeValue()); this.numExceptions = Integer.parseInt(((Element) document.getElementsByTagName("num-exceptions").item(0)).getFirstChild().getNodeValue()); this.wikiText = ((Element) document.getElementsByTagName("wiki").item(0)).getFirstChild().getNodeValue(); } catch (Exception e) { util.Logger.singleton().error(e); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private void createNodes() { try { URL url = this.getClass().getResource(this.nodeFileName); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); // BufferedReader inNodes = new BufferedReader(new // FileReader("NodesFile.txt")); 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(this.edgeFileName); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); // BufferedReader inEdges = new BufferedReader(new // FileReader("EdgesFile.txt")); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { // TODO �Զ���� catch �� e.printStackTrace(); } catch (IOException e) { // TODO �Զ���� catch �� e.printStackTrace(); } /* * for(Myparser.Nd x:FreeConnectTest.pNd){ Node n = new Node(x.id, * x.type); n.label = x.label; node.add(n); } for(Myparser.Ed * x:FreeConnectTest.pEd) edge.add(new Edge(x.id, x.source.id, * x.target.id)); */ }
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 void run() { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); log.trace("passing in cookies: ", cookies); connection.setRequestProperty("Cookie", cookies); connection.getContent(); } catch (Exception e) { log.error(e); } }
00
Code Sample 1: private void createJarArchive(File archiveFile, List<File> filesToBeJared, File base) throws Exception { FileOutputStream stream = new FileOutputStream(archiveFile); JarOutputStream out = new JarOutputStream(stream); for (File tobeJared : filesToBeJared) { if (tobeJared == null || !tobeJared.exists() || tobeJared.isDirectory()) continue; String entryName = tobeJared.getAbsolutePath().substring(base.getAbsolutePath().length() + 1).replace("\\", "/"); JarEntry jarEntry = new JarEntry(entryName); jarEntry.setTime(tobeJared.lastModified()); out.putNextEntry(jarEntry); FileInputStream in = new FileInputStream(tobeJared); IOUtils.copy(in, out); IOUtils.closeQuietly(in); out.closeEntry(); } out.close(); stream.close(); System.out.println("Generated file: " + archiveFile); } Code Sample 2: private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); }
11
Code Sample 1: public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } } Code Sample 2: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); }
00
Code Sample 1: public static String getCssFile(String url) { StringBuffer buffer = new StringBuffer(); try { buffer = new StringBuffer(); URL urlToCrawl = new URL(url); URLConnection urlToCrawlConnection = urlToCrawl.openConnection(); urlToCrawlConnection.setRequestProperty("User-Agent", "USER_AGENT"); urlToCrawlConnection.setRequestProperty("Referer", "REFERER"); urlToCrawlConnection.setUseCaches(false); InputStreamReader isr = new InputStreamReader(urlToCrawlConnection.getInputStream()); BufferedReader in = new BufferedReader(isr); String str; while ((str = in.readLine()) != null) buffer.append(str); FileOutputStream fos = new FileOutputStream("c:\\downloads\\" + System.currentTimeMillis() + ".css"); Writer out = new OutputStreamWriter(fos); out.write(buffer.toString()); out.close(); } catch (Exception e) { System.out.println("Error Downloading css file" + e); } return buffer.toString(); } Code Sample 2: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { URL url = new URL("http://pubsubhubbub.appspot.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("hub.mode=publish&hub.url=" + req.getParameter("url")); out.flush(); out.close(); conn.getResponseCode(); try { resp.sendRedirect(req.getParameter("from")); } catch (Exception e) { } }
11
Code Sample 1: 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(); } } Code Sample 2: private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); }
00
Code Sample 1: private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } } Code Sample 2: private boolean doPost(String content) throws IOException { logger.debug("Service Registry PutRecordHandler: " + baseurl.toString()); logger.debug("**** Service Registry PutRecord Request ****\n " + content); HttpURLConnection huc = (HttpURLConnection) (baseurl.openConnection()); huc.setRequestMethod("POST"); huc.setDoOutput(true); ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes()); OutputStream out = huc.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream bis = new BufferedInputStream(in); int count = 0; while ((count = bis.read(buffer)) != -1) { out.write(buffer, 0, count); } out.close(); int code = huc.getResponseCode(); logger.debug("Service Registry Response Code: " + code); if (code == 200) { return true; } else return false; }
11
Code Sample 1: public static String crypt(String password, String salt) throws java.security.NoSuchAlgorithmException { int saltEnd; int len; int value; int i; MessageDigest hash1; MessageDigest hash2; byte[] digest; byte[] passwordBytes; byte[] saltBytes; StringBuffer result; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if ((saltEnd = salt.indexOf('$')) != -1) { salt = salt.substring(0, saltEnd); } if (salt.length() > 8) { salt = salt.substring(0, 8); } hash1 = MessageDigest.getInstance("MD5"); hash1.update(password.getBytes()); hash1.update(magic.getBytes()); hash1.update(salt.getBytes()); hash2 = MessageDigest.getInstance("MD5"); hash2.update(password.getBytes()); hash2.update(salt.getBytes()); hash2.update(password.getBytes()); digest = hash2.digest(); for (len = password.length(); len > 0; len -= 16) { hash1.update(digest, 0, len > 16 ? 16 : len); } passwordBytes = password.getBytes(); for (i = password.length(); i > 0; i >>= 1) { if ((i & 1) == 1) { hash1.update((byte) 0); } else { hash1.update(passwordBytes, 0, 1); } } result = new StringBuffer(magic); result.append(salt); result.append("$"); digest = hash1.digest(); saltBytes = salt.getBytes(); for (i = 0; i < 1000; i++) { hash2.reset(); if ((i & 1) == 1) { hash2.update(passwordBytes); } else { hash2.update(digest); } if (i % 3 != 0) { hash2.update(saltBytes); } if (i % 7 != 0) { hash2.update(passwordBytes); } if ((i & 1) != 0) { hash2.update(digest); } else { hash2.update(passwordBytes); } digest = hash2.digest(); } value = ((digest[0] & 0xff) << 16) | ((digest[6] & 0xff) << 8) | (digest[12] & 0xff); result.append(to64(value, 4)); value = ((digest[1] & 0xff) << 16) | ((digest[7] & 0xff) << 8) | (digest[13] & 0xff); result.append(to64(value, 4)); value = ((digest[2] & 0xff) << 16) | ((digest[8] & 0xff) << 8) | (digest[14] & 0xff); result.append(to64(value, 4)); value = ((digest[3] & 0xff) << 16) | ((digest[9] & 0xff) << 8) | (digest[15] & 0xff); result.append(to64(value, 4)); value = ((digest[4] & 0xff) << 16) | ((digest[10] & 0xff) << 8) | (digest[5] & 0xff); result.append(to64(value, 4)); value = digest[11] & 0xff; result.append(to64(value, 2)); return result.toString(); } Code Sample 2: private String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
11
Code Sample 1: public static void importDocumentLines(Connection conn, String originDocumentID, String destinationDocumentID) throws SQLException { boolean defaultAutoCommit = conn.getAutoCommit(); String sqlQuery = "select ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice from tbl_DocumentItem where DocumentID=?"; String sqlInsert = "insert into tbl_DocumentItem (ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice,DocumentID) values (?,?,?,?,?,?,?,?,?)"; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; try { pstmt1 = conn.prepareStatement(sqlQuery); pstmt2 = conn.prepareStatement(sqlInsert); conn.setAutoCommit(false); pstmt1.setString(1, originDocumentID); ResultSet rs = pstmt1.executeQuery(); while (rs.next()) { pstmt2.setInt(1, rs.getInt(1)); pstmt2.setString(2, rs.getString(2)); pstmt2.setDouble(3, rs.getDouble(3)); pstmt2.setDouble(4, rs.getDouble(4)); pstmt2.setDouble(5, rs.getDouble(5)); pstmt2.setDouble(6, rs.getDouble(6)); pstmt2.setDouble(7, rs.getDouble(7)); pstmt2.setDouble(8, rs.getDouble(8)); pstmt2.setString(9, destinationDocumentID); pstmt2.executeUpdate(); } rs.close(); conn.commit(); } catch (SQLException ex) { conn.rollback(); } finally { conn.setAutoCommit(defaultAutoCommit); if (pstmt1 != null) pstmt1.close(); if (pstmt2 != null) pstmt2.close(); } } Code Sample 2: public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
00
Code Sample 1: public static String obterConteudoSite(String u) { URL url; try { url = new URL(u); URLConnection conn = null; if (proxy != null) conn = url.openConnection(proxy.getProxy()); else conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); String line; StringBuilder resultado = new StringBuilder(); while ((line = rd.readLine()) != null) { resultado.append(line); resultado.append("\n"); } rd.close(); return resultado.toString(); } catch (MalformedURLException e) { throw new AlfredException("Não foi possível obter contato com o site " + u, e); } catch (IOException e) { throw new AlfredException("Não foi possível obter contato com o site " + u, e); } } Code Sample 2: public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException { if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength); if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'"); HashCash result = new HashCash(); MessageDigest md = MessageDigest.getInstance("SHA1"); result.myResource = resource; result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions); result.myDate = date; result.myVersion = version; String prefix; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); switch(version) { case 0: prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); md.reset(); md.update(result.myToken.getBytes()); result.myValue = numberOfLeadingZeros(md.digest()); break; case 1: result.myValue = value; prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); break; default: throw new IllegalArgumentException("Only supported versions are 0 and 1"); } return result; }
00
Code Sample 1: public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { StringBuilder sb = new StringBuilder(); URL url = new URL("https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=google"); URLConnection connection = url.openConnection(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) sb.append(line); JSONObject json = new JSONObject(sb.toString()); sb.setLength(0); JSONObject responseData = (JSONObject) json.get("responseData"); JSONArray results = (JSONArray) responseData.get("results"); for (int i = 0; i < results.length(); i++) { JSONObject result = (JSONObject) results.get(i); sb.append(result.get("title")).append("\n\n"); } TextView tv = (TextView) findViewById(R.id.textView); tv.setText(sb.toString()); } catch (Exception e) { } }
00
Code Sample 1: public void update() { new Thread(new Runnable() { @Override public void run() { try { jButton1.setEnabled(false); jButton2.setEnabled(false); URL url = new URL(updatePath + "currentVersion.txt"); URLConnection con = url.openConnection(); con.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; for (int i = 0; (line = in.readLine()) != null; i++) { URL fileUrl = new URL(updatePath + line); URLConnection filecon = fileUrl.openConnection(); InputStream stream = fileUrl.openStream(); int oneChar, count = 0; int size = filecon.getContentLength(); jProgressBar1.setMaximum(size); jProgressBar1.setValue(0); File testFile = new File(line); String build = ""; for (String dirtest : line.split("/")) { build += dirtest; if (!build.contains(".")) { File dirfile = new File(build); if (!dirfile.exists()) { dirfile.mkdir(); } } build += "/"; } if (testFile.length() == size) { } else { transferFile(line, fileUrl, size); if (line.endsWith("documents.zip")) { ZipInputStream in2 = new ZipInputStream(new FileInputStream(line)); ZipEntry entry; String pathDoc = line.split("documents.zip")[0]; File docDir = new File(pathDoc + "documents"); if (!docDir.exists()) { docDir.mkdir(); } while ((entry = in2.getNextEntry()) != null) { String outFilename = pathDoc + "documents/" + entry.getName(); OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } in2.close(); } if (line.endsWith("mysql.zip")) { ZipFile zipfile = new ZipFile(line); Enumeration entries = zipfile.entries(); String pathDoc = line.split("mysql.zip")[0]; File docDir = new File(pathDoc + "mysql"); if (!docDir.exists()) { docDir.mkdir(); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(pathDoc + "mysql/" + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); InputStream in2 = zipfile.getInputStream(entry); OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName())); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } in2.close(); out.close(); } } } jProgressBar2.setValue(i + 1); labelFileProgress.setText((i + 1) + "/" + numberFiles); } labelStatus.setText("Update Finished"); jButton1.setVisible(false); jButton2.setText("Finished"); jButton1.setEnabled(true); jButton2.setEnabled(true); } catch (IOException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } Code Sample 2: protected InputStream openStreamInternal(String userAgent, Iterator mimeTypes, Iterator encodingTypes) throws IOException { if (stream != null) return stream; hasBeenOpened = true; URL url = null; try { url = buildURL(); } catch (MalformedURLException mue) { throw new IOException("Unable to make sense of URL for connection"); } if (url == null) return null; URLConnection urlC = url.openConnection(); if (urlC instanceof HttpURLConnection) { if (userAgent != null) urlC.setRequestProperty(HTTP_USER_AGENT_HEADER, userAgent); if (mimeTypes != null) { String acceptHeader = ""; while (mimeTypes.hasNext()) { acceptHeader += mimeTypes.next(); if (mimeTypes.hasNext()) acceptHeader += ","; } urlC.setRequestProperty(HTTP_ACCEPT_HEADER, acceptHeader); } if (encodingTypes != null) { String encodingHeader = ""; while (encodingTypes.hasNext()) { encodingHeader += encodingTypes.next(); if (encodingTypes.hasNext()) encodingHeader += ","; } urlC.setRequestProperty(HTTP_ACCEPT_ENCODING_HEADER, encodingHeader); } contentType = urlC.getContentType(); contentEncoding = urlC.getContentEncoding(); } return (stream = urlC.getInputStream()); }
00
Code Sample 1: public void run() throws Exception { logger.debug("#run enter"); logger.debug("#run lineId : " + lineId); logger.debug("#run quantityNew : " + quantityNew); logger.debug("#run priceNew : " + priceNew); ResultSet rs = null; PreparedStatement ps = null; try { connection.setAutoCommit(false); Integer itemId = null; Integer quantity = null; ps = connection.prepareStatement(SQL_SELECT_ORDER_LINE); ps.setInt(1, lineId); rs = ps.executeQuery(); while (rs.next()) { itemId = rs.getInt("ITEM_ID"); quantity = rs.getInt("QUANTITY"); } rs.close(); ps.close(); ps = connection.prepareStatement(SQL_UPDATE_ITEM_BALANCE); ps.setInt(1, quantityNew - quantity); ps.setInt(2, itemId); ps.executeUpdate(); ps = connection.prepareStatement(SQL_UPDATE_ORDER_LINE); ps.setDouble(1, priceNew); ps.setInt(2, quantityNew); ps.setInt(3, lineId); ps.executeUpdate(); ps.close(); ps.close(); connection.commit(); } catch (SQLException ex) { logger.error("SQLException", ex); connection.rollback(); throw new Exception("Не удалось обновить позицию в заказе. Ошибка : " + ex.getMessage()); } finally { connection.setAutoCommit(true); } logger.debug("#run exit"); } Code Sample 2: @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isTraceEnabled()) { log.trace("doGet(requestURI=" + request.getRequestURI() + ")"); } ServletConfig sc = getServletConfig(); String uriPrefix = request.getContextPath() + "/" + request.getServletPath(); String resUri = request.getRequestURI().substring(uriPrefix.length()); if (log.isTraceEnabled()) { log.trace("Request for resource '" + resUri + "'"); } boolean allowAccess = true; String prefixesSpec = sc.getInitParameter(PARAM_ALLOWED_PREFIXES); if (null != prefixesSpec && prefixesSpec.length() > 0) { String[] prefixes = prefixesSpec.split(";"); allowAccess = false; if (log.isTraceEnabled()) { log.trace("allowedPrefixes specified; checking access"); } for (String prefix : prefixes) { if (log.isTraceEnabled()) { log.trace("Checking resource URI '" + resUri + "' against allowed prefix '" + prefix + "'"); } if (resUri.startsWith(prefix)) { if (log.isTraceEnabled()) { log.trace("Found matching prefix for resource URI '" + resUri + "': '" + prefix + "'"); } allowAccess = true; break; } } } if (!allowAccess) { if (log.isWarnEnabled()) { log.warn("Requested for resource that does not match with" + " allowed prefixes: " + resUri); } response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String resPrefix = sc.getInitParameter(PARAM_RESOURCE_PREFIX); if (null != resPrefix && resPrefix.length() > 0) { if (log.isTraceEnabled()) { log.trace("resourcePrefix specified: " + resPrefix); } if (resPrefix.endsWith("/")) { resUri = resPrefix + resUri; } else { resUri = resPrefix + "/" + resUri; } } resUri = resUri.replaceAll("\\/\\/+", "/"); if (log.isTraceEnabled()) { log.trace("Qualified (prefixed) resource URI: " + resUri); } String baseClassName = sc.getInitParameter(PARAM_BASE_CLASS); if (null == baseClassName || 0 == baseClassName.length()) { if (log.isTraceEnabled()) { log.trace("No baseClass initialization parameter specified; using default: " + ResourceLoaderServlet.class.getName()); } baseClassName = ResourceLoaderServlet.class.getName(); } else { if (log.isTraceEnabled()) { log.trace("Using baseClass: " + baseClassName); } } Class baseClass; try { baseClass = Class.forName(baseClassName); } catch (ClassNotFoundException ex) { throw new ServletException("Base class '" + baseClassName + "' not found", ex); } URL resUrl = baseClass.getResource(resUri); if (null != resUrl) { if (log.isTraceEnabled()) { log.trace("Sending resource: " + resUrl); } URLConnection urlc = resUrl.openConnection(); response.setContentType(urlc.getContentType()); response.setContentLength(urlc.getContentLength()); response.setStatus(HttpServletResponse.SC_OK); final byte[] buf = new byte[255]; int r = 0; InputStream in = new BufferedInputStream(urlc.getInputStream()); OutputStream out = new BufferedOutputStream(response.getOutputStream()); do { r = in.read(buf, 0, 255); if (r > 0) { out.write(buf, 0, r); } } while (r > 0); in.close(); out.flush(); out.close(); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found"); } }
00
Code Sample 1: public void loadSourceCode() { if (getResourceName() != null) { String filename = getResourceName() + ".java"; sourceCode = new String("<html><body bgcolor=\"#ffffff\"><pre>"); InputStream is; InputStreamReader isr; CodeViewer cv = new CodeViewer(); URL url; try { url = getClass().getResource(filename); is = url.openStream(); isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); String line = reader.readLine(); while (line != null) { sourceCode += cv.syntaxHighlight(line) + " \n "; line = reader.readLine(); } sourceCode += new String("</pre></body></html>"); } catch (Exception ex) { sourceCode = "Could not load file: " + filename; } } } Code Sample 2: public PluginLoader(URL pluginLocation, ClassLoader loader) { Loader = loader; url = pluginLocation; try { if (url.toString().substring(0, 3).compareTo("http") == 0) { System.out.println("url location is =" + url.toString()); InputStream ips = url.openStream(); Reader r = new InputStreamReader(ips); ParserDelegator parser = new ParserDelegator(); HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback() { public void handleText(char[] dat, int pos) { String data = new String(dat); if (accept(new File("."), data)) fileList.addElement(data); System.out.println("\ngot a file in list" + data); } }; parser.parse(r, callback, false); } else { file = new File(url.getPath()); System.out.println("File location is =" + file.getPath()); String[] tempList = file.list(this); for (int i = 0; i < tempList.length; i++) fileList.add(tempList[i]); } } catch (Exception e) { e.printStackTrace(); } classLoader = new SimpleClassLoader(url, Loader); System.out.println(file.getAbsolutePath()); fillVectors(); }
00
Code Sample 1: public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } } Code Sample 2: private static String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); if (login) { uc.setRequestProperty("Cookie", logincookie + ";" + xfsscookie); } br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; }
00
Code Sample 1: public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 1., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: @Override public void execute() throws ProcessorExecutionException { try { if (getSource().getPaths() == null || getSource().getPaths().size() == 0 || getDestination().getPaths() == null || getDestination().getPaths().size() == 0) { throw new ProcessorExecutionException("No input and/or output paths specified."); } String temp_dir_prefix = getDestination().getPath().getParent().toString() + "/bcc_" + getDestination().getPath().getName() + "_"; SequenceTempDirMgr dirMgr = new SequenceTempDirMgr(temp_dir_prefix, context); dirMgr.setSeqNum(0); Path tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to AdjSetVertex"); Transformer transformer = new OutAdjVertex2AdjSetVertexTransformer(); transformer.setConf(context); transformer.setSrcPath(getSource().getPath()); tmpDir = dirMgr.getTempDir(); transformer.setDestPath(tmpDir); transformer.setMapperNum(getMapperNum()); transformer.setReducerNum(getReducerNum()); transformer.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to LabeledAdjSetVertex"); Vertex2LabeledTransformer l_transformer = new Vertex2LabeledTransformer(); l_transformer.setConf(context); l_transformer.setSrcPath(tmpDir); tmpDir = dirMgr.getTempDir(); l_transformer.setDestPath(tmpDir); l_transformer.setMapperNum(getMapperNum()); l_transformer.setReducerNum(getReducerNum()); l_transformer.setOutputValueClass(LabeledAdjSetVertex.class); l_transformer.execute(); Graph src; Graph dest; Path path_to_remember = tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": SpanningTreeRootChoose"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); GraphAlgorithm choose_root = new SpanningTreeRootChoose(); choose_root.setConf(context); choose_root.setSource(src); choose_root.setDestination(dest); choose_root.setMapperNum(getMapperNum()); choose_root.setReducerNum(getReducerNum()); choose_root.execute(); Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); String root_vertex_id = the_line.substring(SpanningTreeRootChoose.SPANNING_TREE_ROOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("++++++> Chosen the root of spanning tree = " + root_vertex_id); while (true) { System.out.println("++++++>" + dirMgr.getSeqNum() + " Generate the spanning tree rooted at : (" + root_vertex_id + ") from " + tmpDir); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); path_to_remember = tmpDir; GraphAlgorithm spanning = new SpanningTreeGenerate(); spanning.setConf(context); spanning.setSource(src); spanning.setDestination(dest); spanning.setMapperNum(getMapperNum()); spanning.setReducerNum(getReducerNum()); spanning.setParameter(ConstantLabels.ROOT_ID, root_vertex_id); spanning.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + " Test spanning convergence"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm conv_tester = new SpanningConvergenceTest(); conv_tester.setConf(context); conv_tester.setSource(src); conv_tester.setDestination(dest); conv_tester.setMapperNum(getMapperNum()); conv_tester.setReducerNum(getReducerNum()); conv_tester.execute(); long vertexes_out_of_tree = MRConsoleReader.getMapOutputRecordNum(conv_tester.getFinalStatus()); System.out.println("++++++> number of vertexes out of the spanning tree = " + vertexes_out_of_tree); if (vertexes_out_of_tree == 0) { break; } } System.out.println("++++++> From spanning tree to sets of edges"); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm tree2set = new Tree2EdgeSet(); tree2set.setConf(context); tree2set.setSource(src); tree2set.setDestination(dest); tree2set.setMapperNum(getMapperNum()); tree2set.setReducerNum(getReducerNum()); tree2set.execute(); long map_input_records_num = -1; long map_output_records_num = -2; Stack<Path> expanding_stack = new Stack<Path>(); do { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorJoin"); GraphAlgorithm minorjoin = new EdgeSetMinorJoin(); minorjoin.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorjoin.setSource(src); minorjoin.setDestination(dest); minorjoin.setMapperNum(getMapperNum()); minorjoin.setReducerNum(getReducerNum()); minorjoin.execute(); expanding_stack.push(tmpDir); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetJoin"); GraphAlgorithm join = new EdgeSetJoin(); join.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); join.setSource(src); join.setDestination(dest); join.setMapperNum(getMapperNum()); join.setReducerNum(getReducerNum()); join.execute(); map_input_records_num = MRConsoleReader.getMapInputRecordNum(join.getFinalStatus()); map_output_records_num = MRConsoleReader.getMapOutputRecordNum(join.getFinalStatus()); System.out.println("++++++> map in/out : " + map_input_records_num + "/" + map_output_records_num); } while (map_input_records_num != map_output_records_num); while (expanding_stack.size() > 0) { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetExpand"); GraphAlgorithm expand = new EdgeSetExpand(); expand.setConf(context); src = new Graph(Graph.defaultGraph()); src.addPath(expanding_stack.pop()); src.addPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); expand.setSource(src); expand.setDestination(dest); expand.setMapperNum(getMapperNum()); expand.setReducerNum(getReducerNum()); expand.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorExpand"); GraphAlgorithm minorexpand = new EdgeSetMinorExpand(); minorexpand.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorexpand.setSource(src); minorexpand.setDestination(dest); minorexpand.setMapperNum(getMapperNum()); minorexpand.setReducerNum(getReducerNum()); minorexpand.execute(); } System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetSummarize"); GraphAlgorithm summarize = new EdgeSetSummarize(); summarize.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); dest.setPath(getDestination().getPath()); summarize.setSource(src); summarize.setDestination(dest); summarize.setMapperNum(getMapperNum()); summarize.setReducerNum(getReducerNum()); summarize.execute(); dirMgr.deleteAll(); } catch (IOException e) { throw new ProcessorExecutionException(e); } catch (IllegalAccessException e) { throw new ProcessorExecutionException(e); } } Code Sample 2: 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: public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); 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: public static String calculateSHA1(String data, String key) throws NoSuchAlgorithmException, UnsupportedEncodingException { data += key; MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(data.getBytes("iso-8859-1"), 0, data.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
00
Code Sample 1: public static String analyze(List<String> stackLines) { final MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } final Iterator<String> iterator = stackLines.iterator(); if (!iterator.hasNext()) { return null; } try { final String messageLine = iterator.next(); final String exceptionClass = getExceptionClass(messageLine); messageDigest.update(exceptionClass.getBytes("UTF-8")); analyze(exceptionClass, iterator, messageDigest); final byte[] bytes = messageDigest.digest(); final BigInteger bigInt = new BigInteger(1, bytes); final String ret = bigInt.toString(36); return ret; } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } } Code Sample 2: public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
00
Code Sample 1: private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: byte[] makeIDPFXORMask() { if (idpfMask == null) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); String temp = strip(getPrimaryIdentifier()); sha.update(temp.getBytes("UTF-8"), 0, temp.length()); idpfMask = sha.digest(); } catch (NoSuchAlgorithmException e) { System.err.println("No such Algorithm (really, did I misspell SHA-1?"); System.err.println(e.toString()); return null; } catch (IOException e) { System.err.println("IO Exception. check out mask.write..."); System.err.println(e.toString()); return null; } } return idpfMask; }
11
Code Sample 1: protected String readFileUsingFileUrl(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } Code Sample 2: public static String getPageSource(String url) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder source = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) source.append(line); in.close(); return source.toString(); }
11
Code Sample 1: public String hash(String plainTextPassword) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(plainTextPassword.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(org.jboss.seam.util.Hex.encodeHex(rawHash)); } catch (NoSuchAlgorithmException e) { log.error("Digest algorithm #0 to calculate the password hash will not be supported.", digestAlgorithm); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { log.error("The Character Encoding #0 is not supported", charset); throw new RuntimeException(e); } } Code Sample 2: public static String getMD5(String in) { if (in == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(in.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xFF & hash[i]); if (hex.length() == 1) { hex = "0" + hex; } hexString.append(hex); } return hexString.toString(); } catch (Exception e) { Debug.logException(e); } return null; }
00
Code Sample 1: public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: @Before public void BeforeTheTest() throws Exception { URL url = ProfileParserTest.class.getClassLoader().getResource("ca/uhn/hl7v2/conf/parser/tests/example_ack.xml"); URLConnection conn = url.openConnection(); InputStream instream = conn.getInputStream(); if (instream == null) throw new Exception("can't find the xml file"); BufferedReader in = new BufferedReader(new InputStreamReader(instream)); int tmp = 0; StringBuffer buf = new StringBuffer(); while ((tmp = in.read()) != -1) { buf.append((char) tmp); } profileString = buf.toString(); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: @Override public void start() { System.err.println("start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); super.start(); model = new ApplicationModel(); model.setExceptionHandler(new ExceptionHandler() { public void handle(Throwable t) { t.printStackTrace(); } public void handleUncaught(Throwable t) { t.printStackTrace(); } }); model.setApplet(true); model.dom.getOptions().setAutolayout(false); System.err.println("ApplicationModel created @ " + (System.currentTimeMillis() - t0) + " msec"); model.addDasPeersToApp(); System.err.println("done addDasPeersToApp @ " + (System.currentTimeMillis() - t0) + " msec"); try { System.err.println("Formatters: " + DataSourceRegistry.getInstance().getFormatterExtensions()); } catch (Exception ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } ApplicationModel appmodel = model; dom = model.getDocumentModel(); String debug = getParameter("debug"); if (debug != null && !debug.equals("true")) { } int width = getIntParameter("width", 700); int height = getIntParameter("height", 400); String fontParam = getStringParameter("font", ""); String column = getStringParameter("column", ""); String row = getStringParameter("row", ""); String scolor = getStringParameter("color", ""); String srenderType = getStringParameter("renderType", ""); String stimeRange = getStringParameter("timeRange", ""); String sfillColor = getStringParameter("fillColor", ""); String sforegroundColor = getStringParameter("foregroundColor", ""); String sbackgroundColor = getStringParameter("backgroundColor", ""); String title = getStringParameter("plot.title", ""); String xlabel = getStringParameter("plot.xaxis.label", ""); String xrange = getStringParameter("plot.xaxis.range", ""); String xlog = getStringParameter("plot.xaxis.log", ""); String xdrawTickLabels = getStringParameter("plot.xaxis.drawTickLabels", ""); String ylabel = getStringParameter("plot.yaxis.label", ""); String yrange = getStringParameter("plot.yaxis.range", ""); String ylog = getStringParameter("plot.yaxis.log", ""); String ydrawTickLabels = getStringParameter("plot.yaxis.drawTickLabels", ""); String zlabel = getStringParameter("plot.zaxis.label", ""); String zrange = getStringParameter("plot.zaxis.range", ""); String zlog = getStringParameter("plot.zaxis.log", ""); String zdrawTickLabels = getStringParameter("plot.zaxis.drawTickLabels", ""); statusCallback = getStringParameter("statusCallback", ""); timeCallback = getStringParameter("timeCallback", ""); clickCallback = getStringParameter("clickCallback", ""); if (srenderType.equals("fill_to_zero")) { srenderType = "fillToZero"; } setInitializationStatus("readParameters"); System.err.println("done readParameters @ " + (System.currentTimeMillis() - t0) + " msec"); String vap = getParameter("vap"); if (vap != null) { InputStream in = null; try { URL url = new URL(vap); System.err.println("load vap " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); in = url.openStream(); System.err.println("open vap stream " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.doOpen(in, null); System.err.println("done open vap @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.waitUntilIdle(false); System.err.println("done load vap and waitUntilIdle @ " + (System.currentTimeMillis() - t0) + " msec"); Canvas cc = appmodel.getDocumentModel().getCanvases(0); System.err.println("vap height, width= " + cc.getHeight() + "," + cc.getWidth()); width = getIntParameter("width", cc.getWidth()); height = getIntParameter("height", cc.getHeight()); System.err.println("output height, width= " + width + "," + height); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } } appmodel.getCanvas().setSize(width, height); appmodel.getCanvas().revalidate(); appmodel.getCanvas().setPrintingTag(""); dom.getOptions().setAutolayout("true".equals(getParameter("autolayout"))); if (!dom.getOptions().isAutolayout() && vap == null) { if (!row.equals("")) { dom.getController().getCanvas().getController().setRow(row); } if (!column.equals("")) { dom.getController().getCanvas().getController().setColumn(column); } dom.getCanvases(0).getRows(0).setTop("0%"); dom.getCanvases(0).getRows(0).setBottom("100%"); } if (!fontParam.equals("")) { appmodel.canvas.setBaseFont(Font.decode(fontParam)); } JMenuItem item; item = new JMenuItem(new AbstractAction("Reset Zoom") { public void actionPerformed(ActionEvent e) { resetZoom(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(item); overviewMenuItem = new JCheckBoxMenuItem(new AbstractAction("Context Overview") { public void actionPerformed(ActionEvent e) { addOverview(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(overviewMenuItem); if (sforegroundColor != null && !sforegroundColor.equals("")) { appmodel.canvas.setForeground(Color.decode(sforegroundColor)); } if (sbackgroundColor != null && !sbackgroundColor.equals("")) { appmodel.canvas.setBackground(Color.decode(sbackgroundColor)); } getContentPane().setLayout(new BorderLayout()); System.err.println("done set parameters @ " + (System.currentTimeMillis() - t0) + " msec"); String surl = getParameter("url"); String process = getStringParameter("process", ""); String script = getStringParameter("script", ""); if (surl == null) { surl = getParameter("dataSetURL"); } if (surl != null && !surl.equals("")) { DataSource dsource; try { dsource = DataSetURI.getDataSource(surl); System.err.println("get dsource for " + surl + " @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" got dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); } catch (NullPointerException ex) { throw new RuntimeException("No such data source: ", ex); } catch (Exception ex) { ex.printStackTrace(); dsource = null; } DatumRange timeRange1 = null; if (!stimeRange.equals("")) { timeRange1 = DatumRangeUtil.parseTimeRangeValid(stimeRange); TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb != null) { System.err.println("do tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); tsb.setTimeRange(timeRange1); System.err.println("done tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); } } QDataSet ds; if (dsource != null) { TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb == null) { try { System.err.println("do getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); if (dsource.getClass().toString().contains("CsvDataSource")) System.err.println(" WHY IS THIS CsvDataSource!?!?"); ds = dsource == null ? null : dsource.getDataSet(loadInitialMonitor); for (int i = 0; i < Math.min(12, ds.length()); i++) { System.err.printf("ds[%d]=%s\n", i, ds.slice(i)); } System.err.println("loaded ds: " + ds); System.err.println("done getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (Exception ex) { throw new RuntimeException(ex); } } } System.err.println("do setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.setDataSource(dsource); System.err.println("done setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("dataSourceSet"); if (stimeRange != null && !stimeRange.equals("")) { try { System.err.println("wait for idle @ " + (System.currentTimeMillis() - t0) + " msec (due to stimeRange)"); appmodel.waitUntilIdle(true); System.err.println("done wait for idle @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } if (UnitsUtil.isTimeLocation(dom.getTimeRange().getUnits())) { dom.setTimeRange(timeRange1); } } setInitializationStatus("dataSetLoaded"); } System.err.println("done dataSetLoaded @ " + (System.currentTimeMillis() - t0) + " msec"); Plot p = dom.getController().getPlot(); if (!title.equals("")) { p.setTitle(title); } Axis axis = p.getXaxis(); if (!xlabel.equals("")) { axis.setLabel(xlabel); } if (!xrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(xrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!xlog.equals("")) { axis.setLog("true".equals(xlog)); } if (!xdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(xdrawTickLabels)); } axis = p.getYaxis(); if (!ylabel.equals("")) { axis.setLabel(ylabel); } if (!yrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(yrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!ylog.equals("")) { axis.setLog("true".equals(ylog)); } if (!ydrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(ydrawTickLabels)); } axis = p.getZaxis(); if (!zlabel.equals("")) { axis.setLabel(zlabel); } if (!zrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(zrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!zlog.equals("")) { axis.setLog("true".equals(zlog)); } if (!zdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(zdrawTickLabels)); } if (srenderType != null && !srenderType.equals("")) { try { RenderType renderType = RenderType.valueOf(srenderType); dom.getController().getPlotElement().setRenderType(renderType); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } } System.err.println("done setRenderType @ " + (System.currentTimeMillis() - t0) + " msec"); if (!scolor.equals("")) { try { dom.getController().getPlotElement().getStyle().setColor(Color.decode(scolor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sfillColor.equals("")) { try { dom.getController().getPlotElement().getStyle().setFillColor(Color.decode(sfillColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sforegroundColor.equals("")) { try { dom.getOptions().setForeground(Color.decode(sforegroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sbackgroundColor.equals("")) { try { dom.getOptions().setBackground(Color.decode(sbackgroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } surl = getParameter("dataSetURL"); if (surl != null) { if (surl.startsWith("about:")) { setDataSetURL(surl); } else { } } getContentPane().remove(progressComponent); getContentPane().add(model.getCanvas()); System.err.println("done add to applet @ " + (System.currentTimeMillis() - t0) + " msec"); validate(); System.err.println("done applet.validate @ " + (System.currentTimeMillis() - t0) + " msec"); repaint(); appmodel.getCanvas().setVisible(true); initializing = false; repaint(); System.err.println("ready @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("ready"); dom.getController().getPlot().getXaxis().addPropertyChangeListener(Axis.PROP_RANGE, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { timeCallback(String.valueOf(evt.getNewValue())); } }); if (!clickCallback.equals("")) { String clickCallbackLabel = "Applet Click"; int i = clickCallback.indexOf(","); if (i != -1) { int i2 = clickCallback.indexOf("label="); if (i2 != -1) clickCallbackLabel = clickCallback.substring(i2 + 6).trim(); clickCallback = clickCallback.substring(0, i).trim(); } final DasPlot plot = dom.getPlots(0).getController().getDasPlot(); MouseModule mm = new MouseModule(plot, new CrossHairRenderer(plot, null, plot.getXAxis(), plot.getYAxis()), clickCallbackLabel) { @Override public void mousePressed(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseDragged(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseReleased(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } }; plot.getDasMouseInputAdapter().setPrimaryModule(mm); } p.getController().getDasPlot().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getXaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getYaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getZaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); if (getStringParameter("contextOverview", "off").equals("on")) { Runnable run = new Runnable() { public void run() { dom.getController().waitUntilIdle(); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } dom.getController().waitUntilIdle(); doSetOverview(true); } }; new Thread(run).start(); } System.err.println("done start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); }
00
Code Sample 1: private void checkRoundtrip(byte[] content) throws Exception { InputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(); CodecUtil.encodeQuotedPrintableBinary(in, out); in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray())); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); assertEquals(content, out.toByteArray()); } Code Sample 2: public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
00
Code Sample 1: public Book importFromURL(URL url) { InputStream is = null; try { is = url.openStream(); return importFromStream(is, url.toString()); } catch (Exception ex) { throw ModelException.Aide.wrap(ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw ModelException.Aide.wrap(ex); } } } } Code Sample 2: public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; }
11
Code Sample 1: public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } Code Sample 2: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
00
Code Sample 1: private void getInfoFromXML() { final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true); setProgressBarIndeterminateVisibility(true); Thread t3 = new Thread() { public void run() { waiting(200); txtinfo.post(new Runnable() { public void run() { txtinfo.setText("Searching"); } }); try { URL url = new URL(urlAddress); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); XMLHandlerReviews myXMLHandler = new XMLHandlerReviews(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(url.openStream())); if (statuscode != 200 && statuscode != 206) { throw new Exception(); } nReviewsOnPage = myXMLHandler.nItems; statuscode = myXMLHandler.statuscode; if (nReviewsOnPage > 0) { authors = new String[nReviewsOnPage]; reviews = new String[nReviewsOnPage]; ratings = new String[nReviewsOnPage]; titles = new String[nReviewsOnPage]; listtext = new String[nReviewsOnPage]; for (int i = 0; i < nReviewsOnPage; i++) { reviews[i] = myXMLHandler.reviews[i]; authors[i] = myXMLHandler.authors[i]; titles[i] = myXMLHandler.titles[i]; ratings[i] = myXMLHandler.ratings[i]; if (authors[i] == null || authors[i] == "") { authors[i] = "Anonymous"; } if (ratings[i] == null || ratings[i] == "") { listtext[i] = titles[i] + " - " + reviews[i] + " - " + authors[i]; } else { listtext[i] = "Score: " + ratings[i] + " - " + titles[i] + " - " + reviews[i] + " - " + authors[i]; } } nTotalReviews = myXMLHandler.nTotalItems; final int fnmin = iFirstReviewOnPage; final int fnmax = iFirstReviewOnPage + nReviewsOnPage - 1; final int fntotalitems = nTotalReviews; if (nTotalReviews > fnmax) { nextButton.post(new Runnable() { public void run() { nextButton.setVisibility(0); } }); } else { nextButton.post(new Runnable() { public void run() { nextButton.setVisibility(8); } }); } if (iFirstReviewOnPage > 1) { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(0); } }); } else if (nTotalReviews > fnmax) { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(8); } }); } else { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(4); } }); } txtinfo.post(new Runnable() { public void run() { if (title != null && title != "") { txtinfo.setText(title + "\n" + getString(R.string.showing) + " " + fnmin + " " + getString(R.string.through) + " " + fnmax + " " + getString(R.string.of) + " " + fntotalitems); } else { txtinfo.setText(getString(R.string.showing) + " " + fnmin + " " + getString(R.string.through) + " " + fnmax + " " + getString(R.string.of) + " " + fntotalitems); } } }); handlerSetList.sendEmptyMessage(0); } else { txtinfo.post(new Runnable() { public void run() { txtinfo.setText(title + getString(R.string.no_reviews_for_this_album)); } }); } } catch (Exception e) { final Exception ef = e; txtinfo.post(new Runnable() { public void run() { txtinfo.setText(R.string.search_failed); } }); } dialog.dismiss(); handlerDoneLoading.sendEmptyMessage(0); } }; t3.start(); } Code Sample 2: public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } }
11
Code Sample 1: 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(); } } 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: @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: public static void copyFile(File source, File destination) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: private void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } } Code Sample 2: public Project deleteProject(int projectID) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM Projects WHERE id = " + projectID; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); query = "DELETE FROM Projects WHERE id = " + projectID; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; }
00
Code Sample 1: @Override protected Drawing construct() throws IOException { Drawing result; System.out.println("getParameter.datafile:" + getParameter("datafile")); if (getParameter("data") != null) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data"))); result = (Drawing) domi.readObject(0); } else if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); InputStream in = url.openConnection().getInputStream(); try { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in); result = (Drawing) domi.readObject(0); } finally { in.close(); } } else { result = null; } return result; } Code Sample 2: public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } }
11
Code Sample 1: private String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] data = md.digest(); return convertToHex(data); } catch (Exception ex) { ex.printStackTrace(); } return null; } Code Sample 2: 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"); } }
00
Code Sample 1: public void logout(String cookieString) throws NetworkException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_LOGOUT); if (cookieString != null && cookieString.length() != 0) get.setHeader("Cookie", cookieString); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } } Code Sample 2: public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } }
00
Code Sample 1: public boolean limpiarContrincantexRonda(jugadorxDivxRonda unjxdxr) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = 0 " + " WHERE idJugxDivxRnd = " + unjxdxr.getIdJugxDivxRnd(); try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
00
Code Sample 1: protected void saveSelectedFiles() { if (dataList.getSelectedRowCount() == 0) { return; } if (dataList.getSelectedRowCount() == 1) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(dataList.getSelectedRow())); AttachFile entry = (AttachFile) obj; JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(fc.getCurrentDirectory(), entry.getCurrentPath().getName())); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File current = entry.getCurrentPath(); File dest = fc.getSelectedFile(); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return; } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { for (Integer idx : dataList.getSelectedRows()) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(idx)); AttachFile entry = (AttachFile) obj; File current = entry.getCurrentPath(); File dest = new File(fc.getSelectedFile(), entry.getName()); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return; } } Code Sample 2: public static void printResponseHeaders(String address) { logger.info("Address: " + address); try { URL url = new URL(address); URLConnection conn = url.openConnection(); for (int i = 0; ; i++) { String headerName = conn.getHeaderFieldKey(i); String headerValue = conn.getHeaderField(i); if (headerName == null && headerValue == null) { break; } if (headerName == null) { logger.info(headerValue); continue; } logger.info(headerName + " " + headerValue); } } catch (Exception e) { logger.error("Exception Message: " + e.getMessage()); } }
11
Code Sample 1: protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = new ArrayList<Datastream>(); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); tDatastreams.add(tDatastream); tDatastreams.addAll(_zipFile.getFiles(tZipTempFileName)); return tDatastreams; } Code Sample 2: void copyFileAscii(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { System.err.println(ex.toString()); } }
11
Code Sample 1: private boolean copyOldSetupClass(File lastVerPath, File destPath) throws java.io.FileNotFoundException, IOException { byte[] buf; File oldClass = new File(lastVerPath.getAbsolutePath() + File.separator + installClassName_ + ".class"); if (oldClass.exists()) { FileOutputStream out = new FileOutputStream(destPath.getAbsolutePath() + File.separator + installClassName_ + ".class"); FileInputStream in = new FileInputStream(oldClass); buf = new byte[(new Long(oldClass.length())).intValue()]; int read = in.read(buf, 0, buf.length); out.write(buf, 0, read); out.close(); in.close(); return true; } return false; } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { closeQuietly(in); closeQuietly(out); } return success; }
00
Code Sample 1: public static int fileCopy(String strSourceFilePath, String strDestinationFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); File dir = new File(strSourceFilePath); if (!dir.exists()) dir.mkdirs(); File realDir = new File(strDestinationFilePath); if (!realDir.exists()) realDir.mkdirs(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(new File(strSourceFilePath + SEPARATOR + strFileName)); fos = new FileOutputStream(new File(strDestinationFilePath + SEPARATOR + strFileName)); IOUtils.copy(fis, fos); } catch (Exception ex) { return -1; } finally { try { fos.close(); fis.close(); } catch (Exception ex2) { } } return 0; } Code Sample 2: public static void readAsFile(String fileName, String url) { BufferedInputStream in = null; BufferedOutputStream out = null; URLConnection conn = null; try { conn = new URL(url).openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(fileName)); int b; while ((b = in.read()) != -1) { out.write(b); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { } } } }
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 static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
00
Code Sample 1: public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: @Override protected Integer doInBackground() throws Exception { int numOfRows = 0; combinationMap = new HashMap<AnsweredQuestion, Integer>(); combinationMapReverse = new HashMap<Integer, AnsweredQuestion>(); LinkedHashSet<AnsweredQuestion> answeredQuestionSet = new LinkedHashSet<AnsweredQuestion>(); LinkedHashSet<Integer> studentSet = new LinkedHashSet<Integer>(); final String delimiter = ";"; final String typeToProcess = "F"; String line; String[] chunks = new String[9]; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); numOfRows++; if (chunks[2].equals(typeToProcess)) { answeredQuestionSet.add(new AnsweredQuestion(chunks[4], chunks[5])); studentSet.add(new Integer(chunks[0])); } } in.close(); int i = 0; Integer I; for (AnsweredQuestion pair : answeredQuestionSet) { I = new Integer(i++); combinationMap.put(pair, I); combinationMapReverse.put(I, pair); } matrix = new SparseObjectMatrix2D(answeredQuestionSet.size(), studentSet.size()); int lastStudentNumber = -1; AnsweredQuestion pair; in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); pair = null; if (chunks[2].equals(typeToProcess)) { if (Integer.parseInt(chunks[0]) != lastStudentNumber) { lastStudentNumber++; } pair = new AnsweredQuestion(chunks[4], chunks[5]); if (combinationMap.containsKey(pair)) { matrix.setQuick(combinationMap.get(pair), lastStudentNumber, Boolean.TRUE); } } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } supportVector = new int[combinationMap.size()]; ObjectMatrix1D row = null; for (int i = 0; i < combinationMap.size(); i++) { row = matrix.viewRow(i); int sum = 0; for (int k = 0; k < row.size(); k++) { if (row.getQuick(k) != null && row.getQuick(k).equals(Boolean.TRUE)) { sum++; } } supportVector[i] = sum; } applet.combinationMap = this.combinationMap; applet.combinationMapReverse = this.combinationMapReverse; applet.matrix = this.matrix; applet.supportVector = supportVector; System.out.println("data loaded."); return null; }
00
Code Sample 1: private void createContents(final Shell shell) { Package currentPackage = Package.getPackage("org.sf.pkb.gui"); String author = currentPackage.getImplementationVendor(); String version = currentPackage.getImplementationVersion(); if (author == null || author.trim().length() == 0) { author = "Felton Fee"; } if (version != null && version.trim().length() > 0) { version = "V" + version; } else { version = ""; } FormData data = null; shell.setLayout(new FormLayout()); Label label1 = new Label(shell, SWT.NONE); label1.setImage(Resources.IMAGE_PKB); data = new FormData(); data.top = new FormAttachment(0, 20); data.left = new FormAttachment(0, 20); label1.setLayoutData(data); Label label2 = new Label(shell, SWT.NONE); label2.setText(PreferenceDialog.PKBProperty.DEFAULT_rebrand_application_title + " " + version); Font font = new Font(shell.getDisplay(), "Arial", 12, SWT.NONE); label2.setFont(font); data = new FormData(); data.top = new FormAttachment(0, 25); data.left = new FormAttachment(label1, 15); data.right = new FormAttachment(100, -25); label2.setLayoutData(data); CustomSeparator separator1 = new CustomSeparator(shell, SWT.SHADOW_IN | SWT.HORIZONTAL); data = new FormData(); data.top = new FormAttachment(label2, 20); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); separator1.setLayoutData(data); Label label3 = new Label(shell, SWT.NONE); label3.setText("Written by " + author + " <"); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(0, 15); label3.setLayoutData(data); Hyperlink link = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS); link.setText(PKBMain.CONTACT_EMAIL); link.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { Program.launch("mailto:" + PKBMain.CONTACT_EMAIL + "?subject=[" + PKBMain.PRODUCT_ALEX_PKB + "]"); } }); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(label3, 2); link.setLayoutData(data); Label label4 = new Label(shell, SWT.NONE); label4.setText(">"); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(link, 2); data.right = new FormAttachment(100, -20); label4.setLayoutData(data); Label label6 = new Label(shell, SWT.NONE); label6.setText("Web site:"); data = new FormData(); data.top = new FormAttachment(label4, 10); data.left = new FormAttachment(0, 15); label6.setLayoutData(data); Hyperlink link1 = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS); link1.setText(PKBMain.PRODUCT_WEBSITE); link1.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { Program.launch(PKBMain.PRODUCT_WEBSITE); } }); data = new FormData(); data.top = new FormAttachment(label4, 10); data.left = new FormAttachment(label6, 2); link1.setLayoutData(data); Button closeBtn = new Button(shell, SWT.PUSH); closeBtn.setText("Close"); closeBtn.setLayoutData(data); closeBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { shell.close(); } }); data = new FormData(); data.top = new FormAttachment(label6, 10); data.right = new FormAttachment(100, -20); data.bottom = new FormAttachment(100, -10); closeBtn.setLayoutData(data); Button checkVersionBtn = new Button(shell, SWT.PUSH); checkVersionBtn.setText("Check version"); checkVersionBtn.setLayoutData(data); checkVersionBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { URL url = new URL(PKBMain.PRODUCT_WEBSITE + "/latest-version.txt"); Properties prop = new Properties(); prop.load(url.openStream()); Package currentPackage = Package.getPackage("org.sf.pkb.gui"); String version = currentPackage.getImplementationVersion(); if (version == null) { version = ""; } String remoteVersion = prop.getProperty("version") + " b" + prop.getProperty("build"); if (remoteVersion.trim().compareTo(version.trim()) != 0) { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You do not have the latest version. <br/> ").append("The latest version is PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3><A HREF='").append(prop.getProperty("url")).append("' TARGET='_BLANK'>Please download here </a> <br/><br/>").append("<B>It is strongly suggested to backup your knowledge base before install or unzip the new package!</B>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } else { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You already had the latest version - ALEX PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } } catch (Exception ex) { ex.printStackTrace(); } shell.close(); } }); data = new FormData(); data.top = new FormAttachment(label6, 10); data.right = new FormAttachment(closeBtn, -5); data.bottom = new FormAttachment(100, -10); checkVersionBtn.setLayoutData(data); shell.setDefaultButton(closeBtn); } Code Sample 2: public static String downloadJar(URL url) throws IOException { String localFile = null; char[] buf = new char[4096]; int num; localFile = Settings.getFreeTsUserPath() + "lib" + Settings.SLASH + getURLFileName(url); DebugDialog.print("Downloading jar-file " + url + " to " + localFile + ".", 4); InputStreamReader in = new InputStreamReader(url.openStream()); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(localFile)); do { num = in.read(buf, 0, 4096); if (num > 0) { out.write(buf, 0, num); } } while (num > 0); in.close(); out.close(); return localFile; }
00
Code Sample 1: public static MMissing load(URL url) throws IOException { MMissing ret = new MMissing(); InputStream is = url.openStream(); try { Reader r = new InputStreamReader(is); BufferedReader br = new BufferedReader(r); String line; while ((line = br.readLine()) != null) { if (line.length() > 0) { ret.add(line); } } return ret; } finally { is.close(); } } Code Sample 2: public 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) { ; } } }
11
Code Sample 1: public void performOk(final IProject project, final TomcatPropertyPage page) { page.setPropertyValue("tomcat.jdbc.driver", c_drivers.getText()); page.setPropertyValue("tomcat.jdbc.url", url.getText()); page.setPropertyValue("tomcat.jdbc.user", username.getText()); page.setPropertyValue("tomcat.jdbc.password", password.getText()); File lib = new File(page.tomcatHome.getText(), "lib"); if (!lib.exists()) { lib = new File(new File(page.tomcatHome.getText(), "common"), "lib"); if (!lib.exists()) { Logger.log(Logger.ERROR, "Not properly location of Tomcat Home at :: " + lib); throw new IllegalStateException("Not properly location of Tomcat Home"); } } final File conf = new File(page.tomcatHome.getText(), "conf/Catalina/localhost"); if (!conf.exists()) { final boolean create = NexOpenUIActivator.getDefault().getTomcatConfProperty(); if (create) { if (Logger.getLog().isDebugEnabled()) { Logger.getLog().debug("Create directory " + conf); } try { conf.mkdirs(); } catch (final SecurityException se) { Logger.getLog().error("Retrieved a Security exception creating " + conf, se); Logger.log(Logger.ERROR, "Not created " + conf + " directory. Not enough privilegies. Message :: " + se.getMessage()); } } } String str_driverLibrary = LIBRARIES.get(c_drivers.getText()); if ("<mysql_driver>".equals(str_driverLibrary)) { str_driverLibrary = NexOpenUIActivator.getDefault().getMySQLDriver(); } final File driverLibrary = new File(lib, str_driverLibrary); if (!driverLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + str_driverLibrary)); fos = new FileOutputStream(driverLibrary); IOUtils.copy(driver, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the driver jar file to Tomcat", e); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } page.processTomcatCfg(c_drivers.getText(), url.getText(), username.getText(), password.getText()); } Code Sample 2: public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); }
00
Code Sample 1: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); } 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 Reader getReader(String fname) throws IOException { InputStream is; if (isUrl(fname)) { URL url = new URL(fname); is = url.openStream(); } else { is = new FileInputStream(fname); } if (fname.endsWith(".zip")) { is = new ZipInputStream(is); } else if (fname.endsWith(".gz") || fname.endsWith(".gzip")) { is = new GZIPInputStream(is); } return new InputStreamReader(is); } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; } Code Sample 2: private String hashMD5(String strToHash) throws Exception { try { byte[] bHash = new byte[strToHash.length() * 2]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(strToHash.getBytes("UTF-16LE")); bHash = md.digest(); StringBuffer hexString = new StringBuffer(); for (byte element : bHash) { String strTemp = Integer.toHexString(element); hexString.append(strTemp.replaceAll("f", "")); } return hexString.toString(); } catch (NoSuchAlgorithmException duu) { throw new Exception("NoSuchAlgorithmException: " + duu.getMessage()); } }
00
Code Sample 1: @SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } } Code Sample 2: @Override public ArrayList<String> cacheAgeingProcess(int numberOfDays) throws DatabaseException { IMAGE_LIFETIME = numberOfDays; PreparedStatement statement = null; ArrayList<String> ret = new ArrayList<String>(); try { statement = getConnection().prepareStatement(SELECT_ITEMS_FOR_DELETION_STATEMENT); ResultSet rs = statement.executeQuery(); int i = 0; int rowsAffected = 0; while (rs.next()) { ret.add(rs.getString("imageFile")); i++; } if (i > 0) { statement = getConnection().prepareStatement(DELETE_ITEMS_STATEMENT); rowsAffected = statement.executeUpdate(); } if (rowsAffected == i) { getConnection().commit(); LOGGER.debug("DB has been updated."); LOGGER.debug(i + " images are going to be removed."); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback!"); } } catch (SQLException e) { LOGGER.error(e); } finally { closeConnection(); } return ret; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: private void channelCopy(File source, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
00
Code Sample 1: public static void copy(File src, File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); } Code Sample 2: public static String toPWD(String pwd) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(pwd.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
00
Code Sample 1: private String calculateMD5(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(input.getBytes()); byte[] md5 = digest.digest(); String tmp = ""; String res = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } return res; } Code Sample 2: private AccessControlContext getAccessControlContext(final URL codebase) { PermissionCollection perms = (PermissionCollection) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Policy p = java.security.Policy.getPolicy(); if (p != null) { return p.getPermissions(new CodeSource(null, null)); } else { return null; } } }); if (perms == null) perms = new Permissions(); perms.add(new RuntimePermission("createClassLoader")); Permission p; java.net.URLConnection urlConnection = null; try { urlConnection = codebase.openConnection(); p = urlConnection.getPermission(); } catch (java.io.IOException ioe) { p = null; } if (p != null) perms.add(p); if (p instanceof FilePermission) { String path = p.getName(); int endIndex = path.lastIndexOf(File.separatorChar); if (endIndex != -1) { path = path.substring(0, endIndex + 1); if (path.endsWith(File.separator)) { path += "-"; } perms.add(new FilePermission(path, "read")); } } else { URL locUrl = codebase; if (urlConnection instanceof JarURLConnection) { locUrl = ((JarURLConnection) urlConnection).getJarFileURL(); } String host = locUrl.getHost(); if (host != null && (host.length() > 0)) perms.add(new SocketPermission(host, "connect, accept")); } ProtectionDomain domain = new ProtectionDomain(new CodeSource(codebase, null), perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { domain }); return acc; }
11
Code Sample 1: public static String Md5By32(String plainText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: public static String encrypt(String unencryptedString) { if (StringUtils.isBlank(unencryptedString)) { throw new IllegalArgumentException("Cannot encrypt a null or empty string"); } MessageDigest md = null; String encryptionAlgorithm = Environment.getValue(Environment.PROP_ENCRYPTION_ALGORITHM); try { md = MessageDigest.getInstance(encryptionAlgorithm); } catch (NoSuchAlgorithmException e) { logger.warn("JDK does not support the " + encryptionAlgorithm + " encryption algorithm. Weaker encryption will be attempted."); } if (md == null) { try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException("JDK does not support the SHA-1 or SHA-512 encryption algorithms"); } Environment.setValue(Environment.PROP_ENCRYPTION_ALGORITHM, "SHA-1"); try { Environment.saveConfiguration(); } catch (WikiException e) { logger.info("Failure while saving encryption algorithm property", e); } } try { md.update(unencryptedString.getBytes("UTF-8")); byte raw[] = md.digest(); return encrypt64(raw); } catch (GeneralSecurityException e) { logger.error("Encryption failure", e); throw new IllegalStateException("Failure while encrypting value"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Unsupporting encoding UTF-8"); } }
11
Code Sample 1: public void adicionaCliente(ClienteBean cliente) { PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into cliente(nome,cpf,telefone,cursoCargo,bloqueado,ativo,tipo) values(?,?,?,?,?,?,?)"; try { pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, cliente.getNome()); pstmt.setString(2, cliente.getCPF()); pstmt.setString(3, cliente.getTelefone()); pstmt.setString(4, cliente.getCursoCargo()); pstmt.setString(5, cliente.getBloqueado()); pstmt.setString(6, cliente.getAtivo()); pstmt.setString(7, cliente.getTipo()); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { cliente.setIdCliente(rs.getLong(1)); } connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao inserir cliente.", ex1); } throw new RuntimeException("Erro ao inserir cliente.", ex); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } } Code Sample 2: public void addUserToRealm(final NewUser user) { try { connection.setAutoCommit(false); final String pass, salt; final List<RealmWithEncryptedPass> realmPass = new ArrayList<RealmWithEncryptedPass>(); Realm realm; String username; username = user.username.toLowerCase(locale); PasswordHasher ph = PasswordFactory.getInstance().getPasswordHasher(); pass = ph.hashPassword(user.password); salt = ph.getSalt(); realmPass.add(new RealmWithEncryptedPass(cm.getRealm("null"), PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, "", user.password))); if (user.realms != null) { for (String realmName : user.realms) { realm = cm.getRealm(realmName); realmPass.add(new RealmWithEncryptedPass(realm, PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, realm.getFullRealmName(), user.password))); } user.realms = null; } new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.updatePassword")); psImpl.setString(1, pass); psImpl.setString(2, salt); psImpl.setInt(3, user.userId); psImpl.executeUpdate(); } }); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.addUser")); RealmWithEncryptedPass rwep; RealmDb realm; Iterator<RealmWithEncryptedPass> iter1 = realmPass.iterator(); while (iter1.hasNext()) { rwep = iter1.next(); realm = (RealmDb) rwep.realm; psImpl.setInt(1, realm.getRealmId()); psImpl.setInt(2, user.userId); psImpl.setInt(3, user.domainId); psImpl.setString(4, rwep.password); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUser(user.userId); } catch (GeneralSecurityException e) { log.error(e); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } throw new RuntimeException("Error updating Realms. Unable to continue Operation."); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
00
Code Sample 1: public static int[] sortDescending(float input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] < input[j + 1]) { float mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; } Code Sample 2: public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } }
00
Code Sample 1: public static void loginLetitbit() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to letitbit.com"); HttpPost httppost = new HttpPost("http://letitbit.net/"); httppost.setHeader("Cookie", phpsessioncookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("act", "login")); formparams.add(new BasicNameValuePair("login", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("log")) { logcookie = "log=" + escookie.getValue(); System.out.println(logcookie); } if (escookie.getName().equalsIgnoreCase("pas")) { pascookie = "pas=" + escookie.getValue(); System.out.println(pascookie); } if (escookie.getName().equalsIgnoreCase("host")) { hostcookie = "host=" + escookie.getValue(); System.out.println(hostcookie); } } } Code Sample 2: public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
11
Code Sample 1: private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } Code Sample 2: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
11
Code Sample 1: private void copyFileNFS(String sSource, String sTarget) throws Exception { FileInputStream fis = new FileInputStream(sSource); FileOutputStream fos = new FileOutputStream(sTarget); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buf = new byte[2048]; int i = 0; while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i); bis.close(); bos.close(); fis.close(); fos.close(); } Code Sample 2: private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } }
00
Code Sample 1: public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } } Code Sample 2: public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: public void _getPlotTypes() { boolean gotPlots = false; while (!gotPlots) { try { _myPlotTypes = new Vector[2]; _myPlotTypes[0] = new Vector(); _myPlotTypes[1] = new Vector(); URL dataurl = new URL(getDocumentBase(), plotTypeFile); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String S = readme.readLine(); if (S == null) break; StringTokenizer st = new StringTokenizer(S); _myPlotTypes[0].addElement(st.nextToken()); if (st.hasMoreTokens()) { _myPlotTypes[1].addElement(st.nextToken()); } else { _myPlotTypes[1].addElement((String) _myPlotTypes[0].lastElement()); } } gotPlots = true; } catch (IOException e) { _myPlotTypes[0].removeAllElements(); _myPlotTypes[1].removeAllElements(); gotPlots = false; } } } Code Sample 2: private int testAccesspoint(String s) throws IOException { HttpURLConnection connection = null; try { URL url = new URL(s); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode >= 500) { return 100; } else { return 0; } } finally { if (connection != null) { connection.disconnect(); } } }
11
Code Sample 1: public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } } Code Sample 2: public void truncateLog(long finalZxid) throws IOException { long highestZxid = 0; for (File f : dataDir.listFiles()) { long zxid = isValidSnapshot(f); if (zxid == -1) { LOG.warn("Skipping " + f); continue; } if (zxid > highestZxid) { highestZxid = zxid; } } File[] files = getLogFiles(dataLogDir.listFiles(), highestZxid); boolean truncated = false; for (File f : files) { FileInputStream fin = new FileInputStream(f); InputArchive ia = BinaryInputArchive.getArchive(fin); FileChannel fchan = fin.getChannel(); try { while (true) { byte[] bytes = ia.readBuffer("txtEntry"); if (bytes.length == 0) { throw new EOFException(); } InputArchive iab = BinaryInputArchive.getArchive(new ByteArrayInputStream(bytes)); TxnHeader hdr = new TxnHeader(); deserializeTxn(iab, hdr); if (ia.readByte("EOF") != 'B') { throw new EOFException(); } if (hdr.getZxid() == finalZxid) { long pos = fchan.position(); fin.close(); FileOutputStream fout = new FileOutputStream(f); FileChannel fchanOut = fout.getChannel(); fchanOut.truncate(pos); truncated = true; break; } } } catch (EOFException eof) { } if (truncated == true) { break; } } if (truncated == false) { LOG.error("Not able to truncate the log " + Long.toHexString(finalZxid)); System.exit(13); } }
11
Code Sample 1: public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; } Code Sample 2: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("�����ļ�ʧ�ܣ�Դ�ļ�" + srcFileName + "������!"); return false; } else if (!srcFile.isFile()) { System.out.println("�����ļ�ʧ�ܣ�" + srcFileName + "����һ���ļ�!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("Ŀ���ļ��Ѵ��ڣ�׼��ɾ��!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("ɾ��Ŀ���ļ�" + descFileName + "ʧ��!"); return false; } } else { System.out.println("�����ļ�ʧ�ܣ�Ŀ���ļ�" + descFileName + "�Ѵ���!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("Ŀ���ļ����ڵ�Ŀ¼�����ڣ�����Ŀ¼!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("����Ŀ���ļ����ڵ�Ŀ¼ʧ��!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("���Ƶ����ļ�" + srcFileName + "��" + descFileName + "�ɹ�!"); return true; } catch (Exception e) { System.out.println("�����ļ�ʧ�ܣ�" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
11
Code Sample 1: public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } } Code Sample 2: public static boolean copy(File from, File to) { if (from.isDirectory()) { for (String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { LogUtils.info("Failed to copy " + name + " from " + from + " to " + to, null); return false; } } } else { try { FileInputStream is = new FileInputStream(from); FileChannel ifc = is.getChannel(); FileOutputStream os = makeFile(to); if (USE_NIO) { FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (IOException ex) { LogUtils.warning("Failed to copy " + from + " to " + to, ex); return false; } } long time = from.lastModified(); setLastModified(to, time); long newtime = to.lastModified(); if (newtime != time) { LogUtils.info("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime), null); to.setLastModified(time); long morenewtime = to.lastModified(); return false; } return time == newtime; }
11
Code Sample 1: public static void copyFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } Code Sample 2: private static void copy(String srcFilename, String dstFilename, boolean override) throws IOException, XPathFactoryConfigurationException, SAXException, ParserConfigurationException, XPathExpressionException { File fileToCopy = new File(rootDir + "test-output/" + srcFilename); if (fileToCopy.exists()) { File newFile = new File(rootDir + "test-output/" + dstFilename); if (!newFile.exists() || override) { try { FileChannel srcChannel = new FileInputStream(rootDir + "test-output/" + srcFilename).getChannel(); FileChannel dstChannel = new FileOutputStream(rootDir + "test-output/" + dstFilename).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: private byte[] getCharImage(long chrId) { byte[] imgData = null; try { URL url = new URL("http://img.eve.is/serv.asp?s=256&c=" + chrId); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); int data; try { while ((data = is.read()) >= 0) { os.write(data); } } finally { is.close(); } imgData = os.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return imgData; }