label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: private String md5(String pass) { StringBuffer enteredChecksum = new StringBuffer(); byte[] digest; MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); md5.update(pass.getBytes(), 0, pass.length()); digest = md5.digest(); for (int i = 0; i < digest.length; i++) { enteredChecksum.append(toHexString(digest[i])); } } catch (NoSuchAlgorithmException e) { log.error("Could not create MD5 hash!"); log.error(e.getLocalizedMessage()); log.error(e.getStackTrace()); } return enteredChecksum.toString(); } Code Sample 2: public static String copy(URL url, File dest) throws IOException { if (log.isDebugEnabled()) { log.debug("Fetching: " + url); } IOException error = null; for (int retries = 0; retries < MAX_RETRIES; retries++) { try { OutputStream out = null; InputStream is = null; try { out = new FileOutputStream(dest); if (url.getProtocol().equals("http")) { is = new WebFileInputStream(url); } else { is = url.openStream(); } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); md.update(buf, 0, len); } out.flush(); return bytesToHexString(md.digest()); } catch (ConnectException e) { if (error == null) { error = e; } if (retries < MAX_RETRIES - 1) { log.error(MessageFormat.format("Unable to fetch URL {0}, connection timed out. Will retry...", url.toExternalForm())); try { Thread.sleep(FileHelper.RETRY_SLEEP_TIME); } catch (InterruptedException e2) { } } } catch (SocketTimeoutException e) { if (error == null) { error = e; } if (retries < MAX_RETRIES - 1) { log.error(MessageFormat.format("Unable to fetch URL {0}, timed out. Will retry...", url.toExternalForm())); try { Thread.sleep(FileHelper.RETRY_SLEEP_TIME); } catch (InterruptedException e2) { } } } catch (IOException e) { if (dest.exists()) { try { FileHelper.delete(dest); } catch (IOException e1) { log.error(MessageFormat.format(Messages.getString("FileHelper.UNABLE_DELETE_FILE"), dest), e1); } } throw e; } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(Messages.getString("FileHelper.UNABLE_CLOSE_STREAM"), e); } } if (out != null) { try { out.close(); } catch (IOException e) { log.error(Messages.getString("FileHelper.UNABLE_CLOSE_STREAM"), e); } } } } catch (NoSuchAlgorithmException e) { throw new IOException(MessageFormat.format(Messages.getString("FileHelper.UNABLE_DOWNLOAD_URL"), url), e); } } throw error; }
11
Code Sample 1: public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } this.currentGafFilePath = this.url; try { if (this.httpURL != null) { LOG.info("Reading URL :" + httpURL); InputStream is = this.httpURL.openStream(); int index = this.httpURL.toString().lastIndexOf('/'); String file = this.httpURL.toString().substring(index + 1); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), "tmp-" + file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); is = new FileInputStream(downloadLocation); if (url.endsWith(".gz")) { is = new GZIPInputStream(is); } this.currentGafFile = this.currentGafFilePath.substring(this.currentGafFilePath.lastIndexOf("/") + 1); this.httpURL = null; return is; } else { String file = files[counter++].getName(); this.currentGafFile = file; if (!this.currentGafFilePath.endsWith(file)) currentGafFilePath += file; LOG.info("Returning input stream for the file: " + file); _connect(); ftpClient.changeWorkingDirectory(path); InputStream is = ftpClient.retrieveFileStream(file); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); System.out.println("Download complete....."); is = new FileInputStream(downloadLocation); if (file.endsWith(".gz")) { is = new GZIPInputStream(is); } return is; } } catch (IOException ex) { throw new RuntimeException(ex); } } Code Sample 2: private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
11
Code Sample 1: public Main(String[] args) { boolean encrypt = false; if (args[0].compareTo("-e") == 0) { encrypt = true; } else if (args[0].compareTo("-d") == 0) { encrypt = false; } else { System.out.println("first argument is invalid"); System.exit(-2); } char[] password = new char[args[2].length()]; for (int i = 0; i < args[2].length(); i++) { password[i] = (char) args[2].getBytes()[i]; } try { InitializeCipher(encrypt, password); } catch (Exception e) { System.out.println("error initializing cipher"); System.exit(-3); } try { InputStream is = new FileInputStream(args[1]); OutputStream os; int read, max = 10; byte[] buffer = new byte[max]; if (encrypt) { os = new FileOutputStream(args[1] + ".enc"); os = new CipherOutputStream(os, cipher); } else { os = new FileOutputStream(args[1] + ".dec"); is = new CipherInputStream(is, cipher); } read = is.read(buffer); while (read != -1) { os.write(buffer, 0, read); read = is.read(buffer); } while (read == max) ; os.close(); is.close(); System.out.println(new String(buffer)); } catch (Exception e) { System.out.println("error encrypting/decrypting message:"); e.printStackTrace(); System.exit(-4); } System.out.println("done"); } Code Sample 2: private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line = reader.readLine(); reader.close(); urlcon.disconnect(); return line; }
11
Code Sample 1: private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); } 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 { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static final synchronized String md5(final String data) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data.getBytes()); final byte[] b = md.digest(); return toHexString(b); } catch (final Exception e) { } return ""; }
00
Code Sample 1: private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) { MessageDigest md; byte[] temp_digest, pass_digest; byte[] hex_digest = new byte[35]; byte[] scrambled = scrambledPassword.getBytes(); try { md = MessageDigest.getInstance("MD5"); md.update(plainPassword.getBytes("US-ASCII")); md.update(user.getBytes("US-ASCII")); temp_digest = md.digest(); Utils.bytesToHex(temp_digest, hex_digest, 0); md.update(hex_digest, 0, 32); md.update(salt.getBytes()); pass_digest = md.digest(); Utils.bytesToHex(pass_digest, hex_digest, 3); hex_digest[0] = (byte) 'm'; hex_digest[1] = (byte) 'd'; hex_digest[2] = (byte) '5'; for (int i = 0; i < hex_digest.length; i++) { if (scrambled[i] != hex_digest[i]) { return false; } } } catch (Exception e) { logger.error(e); } return true; } Code Sample 2: public static void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public static String md5Encrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] md5hash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } md5hash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < md5hash.length; i++) { if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; } Code Sample 2: private Scanner getUrlScanner(String strUrl) { URL urlParticipants = null; Scanner scannerParticipants; try { urlParticipants = new URL(strUrl); URLConnection connParticipants; if (StringUtils.isBlank(this.configProxyIp)) { connParticipants = urlParticipants.openConnection(); } else { SocketAddress address = new InetSocketAddress(this.configProxyIp, this.configProxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connParticipants = urlParticipants.openConnection(proxy); } InputStream streamParticipant = connParticipants.getInputStream(); String charSet = StringUtils.substringAfterLast(connParticipants.getContentType(), "charset="); scannerParticipants = new Scanner(streamParticipant, charSet); } catch (MalformedURLException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "MalformedURLException"), new Object[] { urlParticipants.toString() })); } catch (IOException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "IOException"), new Object[] { urlParticipants.toString() })); } return scannerParticipants; }
11
Code Sample 1: public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_CURRENCY")); pst.setString(1, curr.getName()); pst.setInt(2, curr.getIdBase()); pst.setDouble(3, curr.getValue()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from currency"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; } Code Sample 2: public void moveMessage(DBMimeMessage oSrcMsg) throws MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.moveMessage()"); DebugFile.incIdent(); } JDCConnection oConn = null; PreparedStatement oStmt = null; ResultSet oRSet = null; BigDecimal oPg = null; BigDecimal oPos = null; int iLen = 0; try { oConn = ((DBStore) getStore()).getConnection(); oStmt = oConn.prepareStatement("SELECT " + DB.pg_message + "," + DB.nu_position + "," + DB.len_mimemsg + " FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, oSrcMsg.getMessageGuid()); oRSet = oStmt.executeQuery(); if (oRSet.next()) { oPg = oRSet.getBigDecimal(1); oPos = oRSet.getBigDecimal(2); iLen = oRSet.getInt(3); } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oConn.setAutoCommit(false); oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "-" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, ((DBFolder) (oSrcMsg.getFolder())).getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oRSet) { try { oRSet.close(); } catch (Exception ignore) { } } if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (null == oPg) throw new MessagingException("Source message not found"); if (null == oPos) throw new MessagingException("Source message position is not valid"); DBFolder oSrcFldr = (DBFolder) oSrcMsg.getFolder(); MboxFile oMboxSrc = null, oMboxThis = null; try { oMboxSrc = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis.appendMessage(oMboxSrc, oPos.longValue(), iLen); oMboxThis.close(); oMboxThis = null; oMboxSrc.purge(new int[] { oPg.intValue() }); oMboxSrc.close(); oMboxSrc = null; } catch (Exception e) { if (oMboxThis != null) { try { oMboxThis.close(); } catch (Exception ignore) { } } if (oMboxSrc != null) { try { oMboxSrc.close(); } catch (Exception ignore) { } } throw new MessagingException(e.getMessage(), e); } try { oConn = ((DBStore) getStore()).getConnection(); BigDecimal dNext = getNextMessage(); String sCatGuid = getCategory().getString(DB.gu_category); oStmt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.gu_category + "=?," + DB.pg_message + "=? WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, sCatGuid); oStmt.setBigDecimal(2, dNext); oStmt.setString(3, oSrcMsg.getMessageGuid()); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.moveMessage()"); } }
11
Code Sample 1: 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()); } } Code Sample 2: @NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; }
00
Code Sample 1: public HttpEntity execute(final HttpRequestBase request) throws IOException, ClientProtocolException { final HttpResponse response = mClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK | statusCode == HttpStatus.SC_CREATED) { return response.getEntity(); } return null; } Code Sample 2: public void read(Model model, String url) { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) { read(model, conn.getInputStream(), url); } else { read(model, new InputStreamReader(conn.getInputStream(), encoding), url); } } catch (IOException e) { throw new JenaException(e); } }
00
Code Sample 1: public static void compress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(srcFile)); output = new GZIPOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } Code Sample 2: public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
00
Code Sample 1: public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = lst.locationToIndex(e.getPoint()); try { String location = (String) lst.getModel().getElementAt(index), refStr, startStr, stopStr; if (location.indexOf("at chr") != -1) { location = location.substring(location.indexOf("at ") + 3); refStr = location.substring(0, location.indexOf(":")); location = location.substring(location.indexOf(":") + 1); startStr = location.substring(0, location.indexOf("-")); stopStr = location.substring(location.indexOf("-") + 1); moveViewer(refStr, Integer.parseInt(startStr), Integer.parseInt(stopStr)); } else { String hgsid = chooseHGVersion(selPanel.dsn); URL connectURL = new URL("http://genome.ucsc.edu/cgi-bin/hgTracks?hgsid=" + hgsid + "&position=" + location); InputStream urlStream = connectURL.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream)); readUCSCLocation(location, reader); } } catch (Exception exc) { exc.printStackTrace(); } } } Code Sample 2: @SuppressWarnings("unchecked") public ArrayList<GmailContact> getAllContacts() throws GmailException { String query = properties.getString("export_page"); query = query.replace("[RANDOM_INT]", "" + random.nextInt()); int statusCode = -1; GetMethod get = new GetMethod(query); if (log.isInfoEnabled()) log.info("getting all contacts ..."); try { statusCode = client.executeMethod(get); if (statusCode != 200) throw new GmailException("In contacts export page: Status code expected: 200 -> Status code returned: " + statusCode); } catch (HttpException e) { throw new GmailException("HttpException in contacts export page:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in contacts export page:" + e.getMessage()); } finally { get.releaseConnection(); } if (log.isTraceEnabled()) log.trace("accessing contacts export page successful..."); String query_post = properties.getString("outlook_export_page"); PostMethod post = new PostMethod(query_post); post.addRequestHeader("Accept-Encoding", "gzip,deflate"); post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.8"); NameValuePair[] data = { new NameValuePair("at", getCookie("GMAIL_AT")), new NameValuePair("ecf", "o"), new NameValuePair("ac", "Export Contacts") }; post.setRequestBody(data); if (log.isTraceEnabled()) log.trace("getting contacts csv file..."); try { statusCode = client.executeMethod(post); if (statusCode != 200) throw new GmailException("In csv file post: Status code expected: 200 -> Status code returned: " + statusCode); if (log.isTraceEnabled()) log.trace("Gmail: csv charset: " + post.getResponseCharSet()); GMAIL_OUTPUT_CHARSET = post.getResponseCharSet(); InputStreamReader isr = new InputStreamReader(new GZIPInputStream(post.getResponseBodyAsStream()), post.getResponseCharSet()); CSVReader reader = new CSVReader(isr); List csvEntries = reader.readAll(); reader.close(); ArrayList<GmailContact> contacts = new ArrayList<GmailContact>(); MessageDigest m = MessageDigest.getInstance("MD5"); if (log.isTraceEnabled()) log.trace("creating Gmail contacts..."); for (int i = 1; i < csvEntries.size(); i++) { GmailContact contact = new GmailContact(); String[] value = (String[]) csvEntries.get(i); for (int j = 0; j < value.length; j++) { switch(j) { case 0: contact.setName(value[j]); break; case 1: contact.setEmail(value[j]); if (contact.getName() == null) contact.setIdName(value[j]); else contact.setIdName(contact.getName() + value[j]); break; case 2: contact.setNotes(value[j]); break; case 3: contact.setEmail2(value[j]); break; case 4: contact.setEmail3(value[j]); break; case 5: contact.setMobilePhone(value[j]); break; case 6: contact.setPager(value[j]); break; case 7: contact.setCompany(value[j]); break; case 8: contact.setJobTitle(value[j]); break; case 9: contact.setHomePhone(value[j]); break; case 10: contact.setHomePhone2(value[j]); break; case 11: contact.setHomeFax(value[j]); break; case 12: contact.setHomeAddress(value[j]); break; case 13: contact.setBusinessPhone(value[j]); break; case 14: contact.setBusinessPhone2(value[j]); break; case 15: contact.setBusinessFax(value[j]); break; case 16: contact.setBusinessAddress(value[j]); break; case 17: contact.setOtherPhone(value[j]); break; case 18: contact.setOtherFax(value[j]); break; case 19: contact.setOtherAddress(value[j]); break; } } m.update(contact.toString().getBytes()); if (log.isTraceEnabled()) log.trace("setting Md5 Hash..."); contact.setMd5Hash(new BigInteger(m.digest()).toString()); contacts.add(contact); } if (log.isTraceEnabled()) log.trace("Mapping contacts uid..."); Collections.sort(contacts); ArrayList<GmailContact> idList = getAllContactsID(); for (int i = 0; i < idList.size(); i++) { contacts.get(i).setId(idList.get(i).getId()); } if (log.isInfoEnabled()) log.info("getting all contacts info successful..."); return contacts; } catch (HttpException e) { throw new GmailException("HttpException in csv file post:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in csv file post:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new GmailException("No such md5 algorithm " + e.getMessage()); } finally { post.releaseConnection(); } }
11
Code Sample 1: private static void includePodDependencies(Curnit curnit, JarOutputStream jarout) throws IOException { Properties props = new Properties(); Collection<Pod> pods = curnit.getReferencedPods(); for (Pod pod : pods) { PodUuid podId = pod.getPodId(); URL weburl = PodArchiveResolver.getSystemResolver().getUrl(podId); String urlString = ""; if (weburl != null) { String uriPath = weburl.getPath(); String zipPath = CurnitFile.WITHINCURNIT_BASEPATH + uriPath; jarout.putNextEntry(new JarEntry(zipPath)); IOUtils.copy(weburl.openStream(), jarout); jarout.closeEntry(); urlString = CurnitFile.WITHINCURNIT_PROTOCOL + uriPath; } props.put(podId.toString(), urlString); } jarout.putNextEntry(new JarEntry(CurnitFile.PODSREFERENCED_NAME)); props.store(jarout, "pod dependencies"); jarout.closeEntry(); } Code Sample 2: public TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
00
Code Sample 1: public static String getWebContent(String remoteUrl) { StringBuffer sb = new StringBuffer(); try { java.net.URL url = new java.net.URL(remoteUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); } catch (Exception e) { logger.error("获取远程网址内容失败 - " + remoteUrl, e); } return sb.toString(); } Code Sample 2: public static String encrypt(String password, Long digestSeed) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes("UTF-8")); algorithm.update(digestSeed.toString().getBytes("UTF-8")); byte[] messageDigest = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xff & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
00
Code Sample 1: private List _getWeathersFromYahoo(String city) { System.out.println("== get weather information of " + city + " from yahoo =="); try { URL url = new URL(URL + cities.get(city).toString()); InputStream input = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); YahooHandler yh = new YahooHandler(); yh.setCity(city); parser.parse(input, yh); return yh.getWeathers(); } catch (MalformedURLException e) { throw new WeatherException("MalformedURLException"); } catch (IOException e) { throw new WeatherException("无法读取数据。"); } catch (ParserConfigurationException e) { throw new WeatherException("ParserConfigurationException"); } catch (SAXException e) { throw new WeatherException("数据格式错误,无法解析。"); } } 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."); }
11
Code Sample 1: private 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: public static void copy(File _from, File _to) throws IOException { if (_from == null || !_from.exists()) return; FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(_to); in = new FileInputStream(_from); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: private void sendRemoteFiles() throws Exception { if (validParameters()) { URL url = new URL(storageUrlString); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); RequestUtils requestUtils = new RequestUtils(); requestUtils.preRequestAddParameter("senderObj", "FileSender"); requestUtils.preRequestAddParameter("wfiType", "zen"); requestUtils.preRequestAddParameter("portalID", this.portalID); requestUtils.preRequestAddParameter("userID", this.userID); requestUtils.preRequestAddParameter("workflowID", this.workflowID); requestUtils.preRequestAddParameter("jobID", this.jobID); requestUtils.preRequestAddParameter("pidID", this.pidID); requestUtils.preRequestAddParameter("runtimeID", this.runtimeID); requestUtils.preRequestAddParameter("copyhash", getCopyHashStr()); String zipFileName = ZipUtils.getInstance().getUniqueZipFileName(); requestUtils.preRequestAddFile("zipFileName", zipFileName); requestUtils.createPostRequest(); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary()); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); try { httpURLConnection.connect(); OutputStream out = httpURLConnection.getOutputStream(); byte[] preBytes = requestUtils.getPreRequestStringBytes(); out.write(preBytes); out.flush(); ZipUtils.getInstance().sendDirAllFilesToStream(sendFilesDir, out); byte[] postBytes = requestUtils.getPostRequestStringBytes(); out.write(postBytes); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); in.readLine(); in.close(); if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) { throw new Exception("response not HTTP_OK !"); } } catch (Exception e) { e.printStackTrace(); throw new Exception("Cannot connect to: " + storageUrlString, e); } } else { throw new Exception("FilesDir not exist ! or not valid parameters: portalID, userID, workflowID, jobID, pidID, runtimeID !"); } } Code Sample 2: public ProgramProfilingMessageSymbol deleteProfilingMessageSymbol(int id) throws AdaptationException { ProgramProfilingMessageSymbol profilingMessageSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program profiling message " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingMessageSymbol = getProfilingMessageSymbol(resultSet); query = "DELETE FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProfilingMessageSymbol"; 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 profilingMessageSymbol; }
00
Code Sample 1: public boolean isValid(WizardContext context) { if (serviceSelection < 0) { return false; } ServiceReference selection = (ServiceReference) serviceList.getElementAt(serviceSelection); if (selection == null) { return false; } String function = (String) context.getAttribute(ServiceWizard.ATTRIBUTE_FUNCTION); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE_REFERENCE, selection); URL url = selection.getResourceURL(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); JdbcService service = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE, service); return true; } catch (IOException error) { if (!ServiceWizard.FUNCTION_DELETE.equals(function)) { String loc = url.toExternalForm(); String message = messages.format("SelectServiceStep.failed_to_load_service_from_url", loc); context.showErrorDialog(error, message); } else { return true; } } catch (Exception error) { String message = messages.format("SelectServiceStep.service_load_error", url.toExternalForm()); context.showErrorDialog(error, message); } return false; } Code Sample 2: protected boolean createFile(final IProject project, final IProgressMonitor monitor, final Template templ, final String sourceUrl, final String destFile, final boolean isBinary) throws IOException, CoreException { URL url; url = new URL(sourceUrl); final URLConnection con = url.openConnection(); final IFile f = project.getFile(replaceVariables(templ.getVariables(), destFile)); createParents(f, monitor); if (isBinary) { f.create(con.getInputStream(), true, monitor); } else { final StringWriter sw = new StringWriter(); final InputStream in = con.getInputStream(); for (; ; ) { final int c = in.read(); if (-1 == c) { break; } sw.write(c); } sw.close(); final String fileText = replaceVariables(templ.getVariables(), sw.toString()); f.create(new ByteArrayInputStream(fileText.getBytes()), true, monitor); } return true; }
11
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } }
11
Code Sample 1: public void unzip(String resource) { File f = new File(resource); if (!f.exists()) throw new RuntimeException("The specified resources does not exist (" + resource + ")"); String parent = f.getParent().toString(); try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(resource); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { log.info("Extracting archive entry: " + entry); String entryPath = new StringBuilder(parent).append(System.getProperty("file.separator")).append(entry.getName()).toString(); if (entry.isDirectory()) { log.info("Creating directory: " + entryPath); (new File(entryPath)).mkdir(); continue; } int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(entryPath); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public void zip_compressFiles() throws Exception { FileInputStream in = null; File f1 = new File("C:\\WINDOWS\\regedit.exe"); File f2 = new File("C:\\WINDOWS\\win.ini"); File file = new File("C:\\" + NTUtil.class.getName() + ".zip"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.putNextEntry(new ZipEntry("regedit.exe")); in = new FileInputStream(f1); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.putNextEntry(new ZipEntry("win.ini")); in = new FileInputStream(f2); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.close(); } Code Sample 2: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) { throw new IOException("FileCopy: no such source file: " + from_file.getPath()); } if (!from_file.isFile()) { throw new IOException("FileCopy: can't copy directory: " + from_file.getPath()); } if (!from_file.canRead()) { throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath()); } if (to_file.isDirectory()) { to_file = new File(to_file, from_file.getName()); } if (to_file.exists()) { if (!to_file.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath()); } int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { throw new IOException("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent(); if (parent == null) { parent = Globals.getDefaultPath(); } 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(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public void storeModule(OWLModuleManager manager, Module module, URI physicalURI, OWLModuleFormat moduleFormat) throws ModuleStorageException, UnknownModuleException { try { OutputStream os; if (!physicalURI.isAbsolute()) { throw new ModuleStorageException("Physical URI must be absolute: " + physicalURI); } if (physicalURI.getScheme().equals("file")) { File file = new File(physicalURI); file.getParentFile().mkdirs(); os = new FileOutputStream(file); } else { URL url = physicalURI.toURL(); URLConnection conn = url.openConnection(); os = conn.getOutputStream(); } Writer w = new BufferedWriter(new OutputStreamWriter(os)); storeModule(manager, module, w, moduleFormat); } catch (IOException e) { throw new ModuleStorageException(e); } } Code Sample 2: public static String md5(String value) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); try { messageDigest.update(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { messageDigest.update(value.getBytes()); } byte[] bytes = messageDigest.digest(); return byteArrayToHexString(bytes); }
11
Code Sample 1: public static String SHA1(String password) throws BusinessException { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(password.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); return hash.toString(16); } catch (java.security.NoSuchAlgorithmException e) { throw new BusinessException(); } } Code Sample 2: public static String hashMD5(String password) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
11
Code Sample 1: public static String getDigestResponse(String user, String password, String method, String requri, String authstr) { String realm = ""; String nonce = ""; String opaque = ""; String algorithm = ""; String qop = ""; StringBuffer digest = new StringBuffer(); String cnonce; String noncecount; String pAuthStr = authstr; int ptr = 0; String response = ""; int i = 0; StringTokenizer st = new StringTokenizer(pAuthStr, ","); StringTokenizer stprob = null; String str = null; String key = null; String value = null; Properties probs = new Properties(); while (st.hasMoreTokens()) { String nextToken = st.nextToken(); stprob = new StringTokenizer(nextToken, "="); key = stprob.nextToken(); value = stprob.nextToken(); if (value.charAt(0) == '"' || value.charAt(0) == '\'') { value = value.substring(1, value.length() - 1); } probs.put(key, value); } digest.append("Digest username=\"" + user + "\", "); digest.append("realm=\""); digest.append(probs.getProperty("realm")); digest.append("\", "); digest.append("nonce=\""); digest.append(probs.getProperty("nonce")); digest.append("\", "); digest.append("uri=\"" + requri + "\", "); cnonce = "abcdefghi"; noncecount = "00000001"; String toDigest = user + ":" + realm + ":" + password; byte[] digestbuffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toDigest.getBytes()); digestbuffer = md.digest(); } catch (Exception e) { System.err.println("Error creating digest request: " + e); return null; } digest.append("qop=\"auth\", "); digest.append("cnonce=\"" + cnonce + "\", "); digest.append("nc=" + noncecount + ", "); digest.append("response=\"" + response + "\""); if (probs.getProperty("opaque") != null) { digest.append(", opaque=\"" + probs.getProperty("opaque") + "\""); } System.out.println("SipProtocol: Digest calculated."); return digest.toString(); } Code Sample 2: private static String genRandomGUID(boolean secure) { String valueBeforeMD5 = ""; String valueAfterMD5 = ""; MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); return valueBeforeMD5; } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); String strTemp = ""; for (int i = 0; i < array.length; i++) { strTemp = (Integer.toHexString(array[i] & 0XFF)); if (strTemp.length() == 1) { valueAfterMD5 = valueAfterMD5 + "0" + strTemp; } else { valueAfterMD5 = valueAfterMD5 + strTemp; } } return valueAfterMD5.toUpperCase(); }
11
Code Sample 1: @Override public String toString() { if (byteArrayOutputStream == null) return "<Unparsed binary data: Content-Type=" + getHeader("Content-Type") + " >"; String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } } Code Sample 2: public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
11
Code Sample 1: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; } Code Sample 2: public void create() throws IOException { FileChannel fc = new FileInputStream(sourceFile).getChannel(); for (RangeArrayElement element : array) { FileChannel fc_ = fc.position(element.starting()); File part = new File(destinationDirectory, "_0x" + Long.toHexString(element.starting()) + ".partial"); FileChannel partfc = new FileOutputStream(part).getChannel(); partfc.transferFrom(fc_, 0, element.getSize()); partfc.force(true); partfc.close(); } fc.close(); }
00
Code Sample 1: private synchronized boolean saveU(URL url, String typeFlag, byte[] arrByte) { BufferedReader buffReader = null; BufferedOutputStream buffOS = null; URLConnection urlconnection = null; char flagChar = '0'; boolean flag = true; try { urlconnection = url.openConnection(); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); urlconnection.setUseCaches(false); urlconnection.setRequestProperty("Content-type", "application/octet-stream"); buffOS = new BufferedOutputStream(urlconnection.getOutputStream()); buffOS.write((byte[]) typeFlag.getBytes()); buffOS.write(arrByte); buffOS.flush(); if (Config.DEBUG) System.out.println("Applet output file successfully! "); buffReader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream())); StringBuffer stringBuff = new StringBuffer(); String serReturnMess = buffReader.readLine(); if (Config.DEBUG) System.out.println("Applet check status successfully! " + serReturnMess); flagChar = '2'; if (serReturnMess != null) { stringBuff.append(serReturnMess); serReturnMess = serReturnMess.substring(serReturnMess.indexOf(32)).trim() + '2'; flagChar = serReturnMess.charAt(0); } while ((serReturnMess = buffReader.readLine()) != null) { if (serReturnMess.length() <= 0) break; } } catch (Throwable e) { e.printStackTrace(); return false; } finally { try { if (buffOS != null) buffOS.close(); if (buffReader != null) buffReader.close(); } catch (Throwable e) { e.printStackTrace(); } if (flagChar == '2' || flagChar == '3') flag = true; else flag = false; } return flag; } Code Sample 2: public static InputStream openStream(URL url) { try { URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); } catch (IOException e) { throw new IORuntimeException(e); } }
11
Code Sample 1: protected void updateJava2ScriptProject(String prjFolder, String binRelative) { try { File cpFile = new File(prjFolder, ".classpath"); FileInputStream fis = new FileInputStream(cpFile); String classpath = J2SLaunchingUtil.readAFile(fis); if (classpath != null) { boolean needUpdate = false; if (classpath.indexOf("ECLIPSE_SWT") == -1 && classpath.indexOf("SWT_LIBRARY") == -1 && classpath.indexOf("eclipse.swt") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry kind=\"var\" path=\"ECLIPSE_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_SWT") == -1 && classpath.indexOf("ajaxswt.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_SWT_SRC\" kind=\"var\" path=\"AJAX_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_RPC") == -1 && classpath.indexOf("ajaxrpc.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_RPC_SRC\" kind=\"var\" path=\"AJAX_RPC\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_PIPE") == -1 && classpath.indexOf("ajaxpipe.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_PIPE_SRC\" kind=\"var\" path=\"AJAX_PIPE\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (needUpdate) { try { FileOutputStream fos = new FileOutputStream(cpFile); fos.write(classpath.getBytes("utf-8")); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } File webinf = new File(prjFolder, "WEB-INF"); webinf.mkdir(); new File(webinf, "classes").mkdir(); File lib = new File(webinf, "lib"); lib.mkdir(); IPath newPath = null; URL starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); String root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxrpc.jar"); File rpcFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(rpcFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxrpc.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxpipe.jar"); File pipeFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(pipeFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxpipe.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } StringBuffer buildxml = new StringBuffer(); buildxml.append("<?xml version=\"1.0\"?>\r\n"); buildxml.append("<project name=\"java2script.servlet.pack\" default=\"pack.war\" basedir=\".\">\r\n"); buildxml.append(" <description>Pack Java2Script Servlet Application</description>\r\n"); buildxml.append("\r\n"); String name = new File(prjFolder).getName(); buildxml.append(" <property name=\"java2script.app.name\" value=\"" + name + "\"/>\r\n"); buildxml.append(" <property name=\"bin.folder\" value=\"${basedir}/../" + binRelative + "\"/>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.war\" depends=\"pack.jar\">\r\n"); buildxml.append(" <tstamp>\r\n"); buildxml.append(" <format property=\"now\" pattern=\"yyyy-MM-dd-HH-mm-ss\"/>\r\n"); buildxml.append(" </tstamp>\r\n"); buildxml.append(" <delete file=\"${basedir}/../${java2script.app.name}.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../${java2script.app.name}.${now}.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/../\">\r\n"); buildxml.append(" <exclude name=\"src/**\"/>\r\n"); buildxml.append(" <exclude name=\"META-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.java\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.class\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" <fileset dir=\"${basedir}/..\">\r\n"); buildxml.append(" <include name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/build.xml\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" <copy file=\"${basedir}/../${java2script.app.name}.${now}.war\"\r\n"); buildxml.append(" tofile=\"${basedir}/../${java2script.app.name}.war\"/>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.jar\">\r\n"); buildxml.append(" <delete file=\"${basedir}/lib/${java2script.app.name}.jar\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/lib/${java2script.app.name}.jar\">\r\n"); buildxml.append(" <fileset dir=\"${bin.folder}\">\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.html\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.js\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.css\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.bmp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.gif\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.png\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpeg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root); String ajaxPath = newPath.toOSString(); String key = "net.sf.j2s.ajax"; int idx = ajaxPath.lastIndexOf(key); if (idx != -1) { ajaxPath = ajaxPath.substring(0, idx) + "net.sf.j2s.lib" + ajaxPath.substring(idx + key.length()); } File libFile = new File(ajaxPath); String j2sRelativePath = FileUtil.toRelativePath(libFile.getAbsolutePath(), webinf.getAbsolutePath()); if (j2sRelativePath.length() > 0 && !j2sRelativePath.endsWith("/")) { j2sRelativePath += "/"; } int slashIndex = j2sRelativePath.lastIndexOf('/', j2sRelativePath.length() - 2); String pluginPath = j2sRelativePath.substring(0, slashIndex); String libPluginPath = j2sRelativePath.substring(slashIndex + 1, j2sRelativePath.length() - 1); buildxml.append(" <target name=\"pack.plugins.j2slib.war\">\r\n"); buildxml.append(" <delete file=\"${basedir}/../plugins.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../plugins.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/" + pluginPath + "/\">\r\n"); buildxml.append(" <include name=\"" + libPluginPath + "/**\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/library.jar\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/META-INF/**\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append("</project>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "build.xml")); fos.write(buildxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } StringBuffer webxml = new StringBuffer(); webxml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"); webxml.append("<!DOCTYPE web-app\r\n"); webxml.append(" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\r\n"); webxml.append(" \"http://java.sun.com/dtd/web-app_2_3.dtd\">\r\n"); webxml.append("<web-app>\r\n"); webxml.append(" <display-name>Java2Script</display-name>\r\n"); webxml.append(" <description>Java2Script application</description>\r\n"); webxml.append(genereateServlet("simplerpc", "net.sf.j2s.ajax.SimpleRPCHttpServlet")); webxml.append(genereateServlet("piperpc", "net.sf.j2s.ajax.CompoundPipeRPCHttpServlet")); webxml.append(" <servlet>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <servlet-class>net.sf.j2s.ajax.SimplePipeHttpServlet</servlet-class>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.query.timeout</param-name>\r\n"); webxml.append(" <param-value>20000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.script.breakout</param-name>\r\n"); webxml.append(" <param-value>1200000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.max.items.per.query</param-name>\r\n"); webxml.append(" <param-value>60</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" </servlet>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplerpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplerpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>piperpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/piperpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplepipe</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append("</web-app>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "web.xml")); fos.write(webxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } } Code Sample 2: public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
00
Code Sample 1: private static Image tryLoadImageFromFile(String filename, String path, int width, int height) { Image image = null; try { URL url; url = new URL("file:" + path + pathSeparator + fixFilename(filename)); if (url.openStream() != null) { image = Toolkit.getDefaultToolkit().getImage(url); } } catch (MalformedURLException e) { } catch (IOException e) { } if (image != null) { return image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH); } else { return null; } } Code Sample 2: private static void copier(FichierElectronique source, FichierElectronique cible) throws IOException { cible.setNom(source.getNom()); cible.setTaille(source.getTaille()); cible.setTypeMime(source.getTypeMime()); cible.setSoumetteur(source.getSoumetteur()); cible.setDateDerniereModification(source.getDateDerniereModification()); cible.setEmprunteur(source.getEmprunteur()); cible.setDateEmprunt(source.getDateEmprunt()); cible.setNumeroVersion(source.getNumeroVersion()); InputStream inputStream = source.getInputStream(); OutputStream outputStream = cible.getOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { try { inputStream.close(); } finally { outputStream.close(); } if (source instanceof FichierElectroniqueDefaut) { FichierElectroniqueDefaut fichierElectroniqueTemporaire = (FichierElectroniqueDefaut) source; fichierElectroniqueTemporaire.deleteTemp(); } } }
11
Code Sample 1: public static String generate(String presentity, String eventPackage) { if (presentity == null || eventPackage == null) { return null; } String date = Long.toString(System.currentTimeMillis()); try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(presentity.getBytes()); md.update(eventPackage.getBytes()); md.update(date.getBytes()); byte[] digest = md.digest(); return toHexString(digest); } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
11
Code Sample 1: public static final synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally."); nsae.printStackTrace(); } } digest.update(data.getBytes()); return encodeHex(digest.digest()); } Code Sample 2: public static final String crypt(final String password, String salt, final String magic) { if (password == null) throw new IllegalArgumentException("Null password!"); if (salt == null) throw new IllegalArgumentException("Null salt!"); if (magic == null) throw new IllegalArgumentException("Null salt!"); byte finalState[]; long l; MessageDigest ctx, ctx1; try { ctx = MessageDigest.getInstance("md5"); ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException ex) { System.err.println(ex); return null; } if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { ctx.update(finalState, 0, pl > 16 ? 16 : pl); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState, 0, 1); } else { ctx.update(password.getBytes(), 0, 1); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { try { ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException e0) { return null; } if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { ctx1.update(finalState, 0, 16); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { ctx1.update(finalState, 0, 16); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } final StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); }
00
Code Sample 1: protected static DynamicJasperDesign generateJasperDesign(DynamicReport dr) throws CoreException { DynamicJasperDesign jd = null; try { if (dr.getTemplateFileName() != null) { log.info("loading template file: " + dr.getTemplateFileName()); log.info("Attemping to find the file directly in the file system..."); File file = new File(dr.getTemplateFileName()); if (file.exists()) { JasperDesign jdesign = JRXmlLoader.load(file); jd = DJJRDesignHelper.downCast(jdesign, dr); } else { log.info("Not found: Attemping to find the file in the classpath..."); URL url = DynamicJasperHelper.class.getClassLoader().getResource(dr.getTemplateFileName()); JasperDesign jdesign = JRXmlLoader.load(url.openStream()); jd = DJJRDesignHelper.downCast(jdesign, dr); } JasperDesignHelper.populateReportOptionsFromDesign(jd, dr); } else { jd = DJJRDesignHelper.getNewDesign(dr); } registerParameters(jd, dr); } catch (JRException e) { throw new CoreException(e.getMessage(), e); } catch (IOException e) { throw new CoreException(e.getMessage(), e); } return jd; } Code Sample 2: public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
11
Code Sample 1: public static boolean copyFile(File sourceFile, File destFile) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(sourceFile).getChannel(); dstChannel = new FileOutputStream(destFile).getChannel(); long pos = 0; long count = srcChannel.size(); if (count > MAX_BLOCK_SIZE) { count = MAX_BLOCK_SIZE; } long transferred = Long.MAX_VALUE; while (transferred > 0) { transferred = dstChannel.transferFrom(srcChannel, pos, count); pos = transferred; } } catch (IOException e) { return false; } finally { if (srcChannel != null) { try { srcChannel.close(); } catch (IOException e) { } } if (dstChannel != null) { try { dstChannel.close(); } catch (IOException e) { } } } return true; } Code Sample 2: public void handleMessage(Message message) throws Fault { InputStream is = message.getContent(InputStream.class); if (is == null) { return; } CachedOutputStream bos = new CachedOutputStream(); try { IOUtils.copy(is, bos); is.close(); bos.close(); sendMsg("Inbound Message \n" + "--------------" + bos.getOut().toString() + "\n--------------"); message.setContent(InputStream.class, bos.getInputStream()); } catch (IOException e) { throw new Fault(e); } }
00
Code Sample 1: public void load(String fileName) { BufferedReader bufReader; loaded = false; vector.removeAllElements(); try { if (fileName.startsWith("http:")) { URL url = new URL(fileName); bufReader = new BufferedReader(new InputStreamReader(url.openStream())); } else bufReader = new BufferedReader(new FileReader(fileName)); String inputLine; while ((inputLine = bufReader.readLine()) != null) { if (listener != null) listener.handleLine(inputLine); else vector.add(inputLine); } bufReader.close(); loaded = true; } catch (IOException e) { errorMsg = e.getMessage(); } } Code Sample 2: public boolean check(Object credentials) { String password = (credentials instanceof String) ? (String) credentials : credentials.toString(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] ha1; if (credentials instanceof Credential.MD5) { ha1 = ((Credential.MD5) credentials).getDigest(); } else { md.update(username.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(realm.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(password.getBytes(StringUtil.__ISO_8859_1)); ha1 = md.digest(); } md.reset(); md.update(method.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(uri.getBytes(StringUtil.__ISO_8859_1)); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nc.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(cnonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(qop.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1)); byte[] digest = md.digest(); return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response)); } catch (Exception e) { Log.warn(e); } return false; }
11
Code Sample 1: public static boolean copyFile(String source, String destination, boolean replace) { File sourceFile = new File(source); File destinationFile = new File(destination); if (sourceFile.isDirectory() || destinationFile.isDirectory()) return false; if (destinationFile.isFile() && !replace) return false; if (!sourceFile.isFile()) return false; if (replace) destinationFile.delete(); try { File dir = destinationFile.getParentFile(); while (dir != null && !dir.exists()) { dir.mkdir(); } DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile), 10240)); DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(sourceFile), 10240)); try { while (inStream.available() > 0) { outStream.write(inStream.readUnsignedByte()); } } catch (EOFException eof) { } inStream.close(); outStream.close(); } catch (IOException ex) { throw new FailedException("Failed to copy file " + sourceFile.getAbsolutePath() + " to " + destinationFile.getAbsolutePath(), ex).setFile(destinationFile.getAbsolutePath()); } return true; } Code Sample 2: public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } }
00
Code Sample 1: protected int doExecuteInsert(PreparedStatement statement, Table data) throws SQLException { ResultSet rs = null; int result = -1; try { lastError = null; result = statement.executeUpdate(); if (!isAutoCommit()) connection.commit(); rs = statement.getGeneratedKeys(); while (rs.next()) { FieldUtils.setValue(data, data.key, rs.getObject(1)); } } catch (SQLException ex) { if (!isAutoCommit()) { lastError = ex; connection.rollback(); LogUtils.log(Level.SEVERE, "Transaction is being rollback. Error: " + ex.toString()); } else { throw ex; } } finally { if (statement != null) statement.close(); if (rs != null) rs.close(); } return result; } Code Sample 2: public void loadXML(URL flux, int status, File file) { try { SAXBuilder sbx = new SAXBuilder(); try { if (file.exists()) { file.delete(); } if (!file.exists()) { URLConnection conn = flux.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(10000); InputStream is = conn.getInputStream(); OutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); out.close(); is.close(); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "Exeption retrieving XML", e); } try { document = sbx.build(new FileInputStream(file)); } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "xml error ", e); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "TsukiQueryError", e); } if (document != null) { root = document.getRootElement(); PopulateDatabase(root, status); } }
11
Code Sample 1: static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); } Code Sample 2: public 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: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
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 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: @LargeTest public void testThreadCheck() throws Exception { ContentResolver resolver = getContext().getContentResolver(); GoogleHttpClient client = new GoogleHttpClient(resolver, "Test", false); try { HttpGet method = new HttpGet(mServerUrl); AndroidHttpClient.setThreadBlocked(true); try { client.execute(method); fail("\"thread forbids HTTP requests\" exception expected"); } catch (RuntimeException e) { if (!e.toString().contains("forbids HTTP requests")) throw e; } finally { AndroidHttpClient.setThreadBlocked(false); } HttpResponse response = client.execute(method); assertEquals("/", EntityUtils.toString(response.getEntity())); } finally { client.close(); } }
11
Code Sample 1: public void run() { try { int id = getID() - 1; String file = id + ".dem"; String data = URLEncoder.encode("file", "UTF-8") + "=" + URLEncoder.encode(file, "UTF-8"); data += "&" + URLEncoder.encode("hash", "UTF-8") + "=" + URLEncoder.encode(getMD5Digest("tf2invite" + file), "UTF-8"); URL url = new URL("http://94.23.189.99/ftp.php"); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); String line; BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { System.out.println(line); if (line.startsWith("demo=")) msg("2The last gather demo has been uploaded successfully: " + line.split("=")[1]); } rd.close(); wr.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private Component createLicensePane(String propertyKey) { if (licesePane == null) { String licenseText = ""; BufferedReader in = null; try { String filename = "conf/LICENSE.txt"; java.net.URL url = FileUtil.toURL(filename); in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while (true) { line = in.readLine(); if (line == null) break; licenseText += line; } } catch (Exception e) { log.error(e); } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } licenseText = StringUtils.replace(licenseText, "<br>", "\n"); licenseText = StringUtils.replace(licenseText, "<p>", "\n\n"); StyleContext context = new StyleContext(); StyledDocument document = new DefaultStyledDocument(context); Style style = context.getStyle(StyleContext.DEFAULT_STYLE); StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER); StyleConstants.setSpaceAbove(style, 4); StyleConstants.setSpaceBelow(style, 4); StyleConstants.setFontSize(style, 14); try { document.insertString(document.getLength(), licenseText, style); } catch (BadLocationException e) { log.error(e); } JTextPane textPane = new JTextPane(document); textPane.setEditable(false); licesePane = new JScrollPane(textPane); } return licesePane; }
11
Code Sample 1: private static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public char check(String password) { if (captchaRandom.equals("null")) { return 's'; } if (captchaRandom.equals("used")) { return 'm'; } String encryptionBase = secret + captchaRandom; if (!alphabet.equals(ALPHABET_DEFAULT) || letters != LETTERS_DEFAULT) { encryptionBase += ":" + alphabet + ":" + letters; } MessageDigest md5; byte[] digest = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; try { md5 = MessageDigest.getInstance("MD5"); md5.update(encryptionBase.getBytes()); digest = md5.digest(); } catch (NoSuchAlgorithmException e) { } String correctPassword = ""; int index; for (int i = 0; i < letters; i++) { index = (digest[i] + 256) % 256 % alphabet.length(); correctPassword += alphabet.substring(index, index + 1); } if (!password.equals(correctPassword)) { return 'w'; } else { captchaRandom = "used"; return 't'; } }
00
Code Sample 1: public static void toZip(File zippedFile, File[] filesToZip, String zipComment, boolean savePath, int compressionLevel) throws IOException, FileNotFoundException, ZipException { if (zippedFile != null && filesToZip != null) { new File(zippedFile.getParent()).mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new CheckedOutputStream(new FileOutputStream(zippedFile), new CRC32()))); if (ZIP_NO_COMPRESSION <= compressionLevel && compressionLevel <= ZIP_MAX_COMPRESSION) out.setLevel(compressionLevel); else out.setLevel(ZIP_MAX_COMPRESSION); if (zipComment != null) out.setComment(zipComment); for (int i = 0; i < filesToZip.length; i++) { BufferedInputStream in; if (savePath) { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(cleanPath(filesToZip[i].getAbsolutePath()))); } else { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(filesToZip[i].getName())); } for (int c = in.read(); c != -1; c = in.read()) out.write(c); in.close(); } out.close(); } else throw new ZipException(MAIN_RESOURCE_BUNDLE.getString("default.ZipException.text")); } 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 String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); 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_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); 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; } Code Sample 2: public static IProject CreateJavaProject(String name, IPath classpath) throws CoreException { // Create and Open New Project in Workspace IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject(name); project.create(null); project.open(null); // Add Java Nature to new Project IProjectDescription desc = project.getDescription(); desc.setNatureIds(new String[] { JavaCore.NATURE_ID}); project.setDescription(desc, null); // Get Java Project Object IJavaProject javaProj = JavaCore.create(project); // Set Output Folder IFolder binDir = project.getFolder("bin"); IPath binPath = binDir.getFullPath(); javaProj.setOutputLocation(binPath, null); // Set Project's Classpath IClasspathEntry cpe = JavaCore.newLibraryEntry(classpath, null, null); javaProj.setRawClasspath(new IClasspathEntry[] {cpe}, null); return project; }
00
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 byte[] hash(String identifier) { if (function.equals("SHA-1")) { try { MessageDigest md = MessageDigest.getInstance(function); md.reset(); byte[] code = md.digest(identifier.getBytes()); byte[] value = new byte[KEY_LENGTH / 8]; int shrink = code.length / value.length; int bitCount = 1; for (int j = 0; j < code.length * 8; j++) { int currBit = ((code[j / 8] & (1 << (j % 8))) >> j % 8); if (currBit == 1) bitCount++; if (((j + 1) % shrink) == 0) { int shrinkBit = (bitCount % 2 == 0) ? 0 : 1; value[j / shrink / 8] |= (shrinkBit << ((j / shrink) % 8)); bitCount = 1; } } return value; } catch (Exception e) { e.printStackTrace(); } } if (function.equals("CRC32")) { CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(identifier.getBytes()); long code = crc32.getValue(); code &= (0xffffffffffffffffL >>> (64 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } if (function.equals("Java")) { int code = identifier.hashCode(); code &= (0xffffffff >>> (32 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } return null; }
11
Code Sample 1: public String digestPassword(String password) { StringBuffer hexString = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); byte[] messageDigest = algorithm.digest(); for (byte b : messageDigest) { hexString.append(Integer.toHexString(0xFF & b)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); } Code Sample 2: static String encodeEmailAsUserId(String email) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(email.toLowerCase().getBytes()); StringBuilder builder = new StringBuilder(); builder.append("1"); for (byte b : md5.digest()) { builder.append(String.format("%02d", new Object[] { Integer.valueOf(b & 0xFF) })); } return builder.toString().substring(0, 20); } catch (NoSuchAlgorithmException ex) { } return ""; }
00
Code Sample 1: private static String executeGet(String urlStr) { StringBuffer result = new StringBuffer(); try { Authentication.doIt(); URL url = new URL(urlStr); System.out.println("Host: " + url.getHost()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result.toString(); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: public BufferedImage processUsingTemp(InputStream input, DjatokaDecodeParam params) throws DjatokaException { File in; try { in = File.createTempFile("tmp", ".jp2"); FileOutputStream fos = new FileOutputStream(in); in.deleteOnExit(); IOUtils.copyStream(input, fos); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } BufferedImage bi = process(in.getAbsolutePath(), params); if (in != null) in.delete(); return bi; }
00
Code Sample 1: private void checkLogin(String email, String password) throws JspTagException { String cryptedPassword; try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(password.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } cryptedPassword = hexString.toString(); crypt.reset(); InitialContext context = new InitialContext(); java.lang.Object homeRef = context.lookup("java:comp/env/ejb/Value"); ValueHome valueHome = (ValueHome) PortableRemoteObject.narrow(homeRef, ValueHome.class); Value value = valueHome.findByPasswordCheck(email, cryptedPassword); pageContext.setAttribute("validLogin", new Boolean(true)); HttpSession session = pageContext.getSession(); session.setAttribute("jspShop.userID", value.getObjectID()); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } catch (ObjectNotFoundException e) { pageContext.setAttribute("validLogin", new Boolean(false)); } catch (NamingException e) { System.err.println("jspShop: Could not initialise context in LoginTag"); e.printStackTrace(); } catch (RemoteException e) { System.err.println("jspShop: Could not connect to container in LoginTag"); } catch (FinderException e) { System.err.println("jspShop: Error using finderQuery in LoginTag"); } } Code Sample 2: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { if (e.getSource() == cancel) { email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } else { StringBuffer errors = new StringBuffer(); if (email.getText().trim().equals("")) errors.append("El campo 'Email' es obligatorio<br/>"); if (name.getText().trim().equals("")) errors.append("El campo 'Nombre' es obligatorio<br/>"); if (subject.getText().trim().equals("")) errors.append("El campo 'T�tulo' es obligatorio<br/>"); if (message.getText().trim().equals("")) errors.append("No hay conrtenido en el mensaje<br/>"); if (errors.length() > 0) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>" + errors.toString() + "</html>", "Error", JOptionPane.ERROR_MESSAGE); } else { try { StringBuffer params = new StringBuffer(); params.append("name=").append(URLEncoder.encode(name.getText(), "UTF-8")).append("&category=").append(URLEncoder.encode((String) category.getSelectedItem(), "UTF-8")).append("&title=").append(URLEncoder.encode(subject.getText(), "UTF-8")).append("&email=").append(URLEncoder.encode(email.getText(), "UTF-8")).append("&id=").append(URLEncoder.encode(MainWindow.getUserPreferences().getUniqueId() + "", "UTF-8")).append("&body=").append(URLEncoder.encode(message.getText(), "UTF-8")); URL url = new URL("http://www.cronopista.com/diccionario2/sendMessage.php"); URLConnection connection = url.openConnection(); Utils.setupProxy(connection); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(params.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>Ha ocurrido un error enviando tu mensaje.<br/>" + "Por favor, int�ntalo m�s tarde o ponte en contacto conmigo a trav�s de www.cronopista.com</html>", "Error", JOptionPane.ERROR_MESSAGE); } } } } Code Sample 2: private String sendToServer(String request) throws IOException { Log.d("test", "request body " + request); String result = null; maybeCreateHttpClient(); HttpPost post = new HttpPost(Config.APP_BASE_URI); post.addHeader("Content-Type", "text/vnd.aexp.json.req"); post.setEntity(new StringEntity(request)); HttpResponse resp = httpClient.execute(post); int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) throw new IOException("HTTP status: " + Integer.toString(status)); DataInputStream is = new DataInputStream(resp.getEntity().getContent()); result = is.readLine(); return result; }
11
Code Sample 1: public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } } Code Sample 2: private void fileMaker() { try { long allData = 0; double a = 10; int range = 0; int blockLength = 0; File newFile = new File(mfr.getFilename() + ".part"); if (newFile.exists()) { newFile.delete(); } ArrayList<DataRange> rangeList = null; byte[] data = null; newFile.createNewFile(); ByteBuffer buffer = ByteBuffer.allocate(mfr.getBlocksize()); FileChannel rChannel = new FileInputStream(inputFileName).getChannel(); FileChannel wChannel = new FileOutputStream(newFile, true).getChannel(); System.out.println(); System.out.print("File completion: "); System.out.print("|----------|"); openConnection(); http.getResponseHeader(); for (int i = 0; i < fileMap.length; i++) { fileOffset = fileMap[i]; if (fileOffset != -1) { rChannel.read(buffer, fileOffset); buffer.flip(); wChannel.write(buffer); buffer.clear(); } else { if (!rangeQueue) { rangeList = rangeLookUp(i); range = rangeList.size(); openConnection(); http.setRangesRequest(rangeList); http.sendRequest(); http.getResponseHeader(); data = http.getResponseBody(mfr.getBlocksize()); allData += http.getAllTransferedDataLength(); } if ((i * mfr.getBlocksize() + mfr.getBlocksize()) < mfr.getLength()) { blockLength = mfr.getBlocksize(); } else { blockLength = (int) ((int) (mfr.getBlocksize()) + (mfr.getLength() - (i * mfr.getBlocksize() + mfr.getBlocksize()))); } buffer.put(data, (range - rangeList.size()) * mfr.getBlocksize(), blockLength); buffer.flip(); wChannel.write(buffer); buffer.clear(); rangeList.remove(0); if (rangeList.isEmpty()) { rangeQueue = false; } } if ((((double) i / ((double) fileMap.length - 1)) * 100) >= a) { progressBar(((double) i / ((double) fileMap.length - 1)) * 100); a += 10; } } newFile.setLastModified(getMTime()); sha = new SHA1(newFile); if (sha.SHA1sum().equals(mfr.getSha1())) { System.out.println("\nverifying download...checksum matches OK"); System.out.println("used " + (mfr.getLength() - (mfr.getBlocksize() * missing)) + " " + "local, fetched " + (mfr.getBlocksize() * missing)); new File(mfr.getFilename()).renameTo(new File(mfr.getFilename() + ".zs-old")); newFile.renameTo(new File(mfr.getFilename())); allData += mfr.getLengthOfMetafile(); System.out.println("really downloaded " + allData); double overhead = ((double) (allData - (mfr.getBlocksize() * missing)) / ((double) (mfr.getBlocksize() * missing))) * 100; System.out.println("overhead: " + df.format(overhead) + "%"); } else { System.out.println("\nverifying download...checksum don't match"); System.out.println("Deleting temporary file"); newFile.delete(); System.exit(1); } } catch (IOException ex) { System.out.println("Can't read or write, check your permissions."); System.exit(1); } }
00
Code Sample 1: public void importarHistoricoDeProventos(File pArquivoXLS, boolean pFiltrarPelaDataDeCorteDoCabecalho, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { int iLinha = -1; String nomeDaColuna = ""; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet plan1 = arquivo.getSheetAt(0); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 2; int quantidadeDeRegistrosEstimada = plan1.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS; String vNomeDePregao, vTipoDaAcao, vDataDaAprovacao, vTipoDoProvento, vDataDoUltimoPrecoCom; BigDecimal vValorDoProvento, vUltimoPrecoCom, vProventoPorPreco; int vProventoPor1Ou1000Acoes, vPrecoPor1Ou1000Acoes; java.sql.Date vUltimoDiaCom; DateFormat formatadorData = new SimpleDateFormat("yyyyMMdd"); DateFormat formatadorPadraoData = DateFormat.getDateInstance(); Row registro; Cell celula; java.util.Date dataLimite = plan1.getRow(0).getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getDateCellValue(); Cell celulaUltimoDiaCom; java.util.Date tmpUltimoDiaCom; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_PROVENTO_EM_DINHEIRO"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_PROVENTO_EM_DINHEIRO(NOME_DE_PREGAO, TIPO_DA_ACAO, DATA_DA_APROVACAO, VALOR_DO_PROVENTO, PROVENTO_POR_1_OU_1000_ACOES, TIPO_DO_PROVENTO, ULTIMO_DIA_COM, DATA_DO_ULTIMO_PRECO_COM, ULTIMO_PRECO_COM, PRECO_POR_1_OU_1000_ACOES, PERC_PROVENTO_POR_PRECO) VALUES(:NOME_DE_PREGAO, :TIPO_DA_ACAO, :DATA_DA_APROVACAO, :VALOR_DO_PROVENTO, :PROVENTO_POR_1_OU_1000_ACOES, :TIPO_DO_PROVENTO, :ULTIMO_DIA_COM, :DATA_DO_ULTIMO_PRECO_COM, :ULTIMO_PRECO_COM, :PRECO_POR_1_OU_1000_ACOES, :PERC_PROVENTO_POR_PRECO)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; final int NUMERO_DA_LINHA_INICIAL = 1; for (iLinha = NUMERO_DA_LINHA_INICIAL; true; iLinha++) { registro = plan1.getRow(iLinha); if (registro != null) { nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.toString(); celulaUltimoDiaCom = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.ordinal()); if (celulaUltimoDiaCom != null) { if (celulaUltimoDiaCom.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpUltimoDiaCom = celulaUltimoDiaCom.getDateCellValue(); if (tmpUltimoDiaCom.compareTo(dataLimite) <= 0 || !pFiltrarPelaDataDeCorteDoCabecalho) { vUltimoDiaCom = new java.sql.Date(celulaUltimoDiaCom.getDateCellValue().getTime()); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.toString(); vNomeDePregao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.toString(); vTipoDaAcao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.ordinal()); try { java.util.Date tmpDataDaAprovacao; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDaAprovacao = celula.getDateCellValue(); } else { tmpDataDaAprovacao = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDaAprovacao = formatadorData.format(tmpDataDaAprovacao); } catch (ParseException ex) { vDataDaAprovacao = celula.getStringCellValue(); } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.toString(); vValorDoProvento = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.toString(); vProventoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.toString(); vTipoDoProvento = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.ordinal()); if (celula != null) { try { java.util.Date tmpDataDoUltimoPrecoCom; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDoUltimoPrecoCom = celula.getDateCellValue(); } else { tmpDataDoUltimoPrecoCom = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDoUltimoPrecoCom = formatadorData.format(tmpDataDoUltimoPrecoCom); } catch (ParseException ex) { vDataDoUltimoPrecoCom = celula.getStringCellValue().trim(); } } else { vDataDoUltimoPrecoCom = ""; } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.toString(); vUltimoPrecoCom = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.toString(); vPrecoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.ordinal()); if (celula != null && celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { vProventoPorPreco = new BigDecimal(String.valueOf(celula.getNumericCellValue())); } else { vProventoPorPreco = null; } stmtDestino.clearParameters(); stmtDestino.setStringAtName("NOME_DE_PREGAO", vNomeDePregao); stmtDestino.setStringAtName("TIPO_DA_ACAO", vTipoDaAcao); stmtDestino.setStringAtName("DATA_DA_APROVACAO", vDataDaAprovacao); stmtDestino.setBigDecimalAtName("VALOR_DO_PROVENTO", vValorDoProvento); stmtDestino.setIntAtName("PROVENTO_POR_1_OU_1000_ACOES", vProventoPor1Ou1000Acoes); stmtDestino.setStringAtName("TIPO_DO_PROVENTO", vTipoDoProvento); stmtDestino.setDateAtName("ULTIMO_DIA_COM", vUltimoDiaCom); stmtDestino.setStringAtName("DATA_DO_ULTIMO_PRECO_COM", vDataDoUltimoPrecoCom); stmtDestino.setBigDecimalAtName("ULTIMO_PRECO_COM", vUltimoPrecoCom); stmtDestino.setIntAtName("PRECO_POR_1_OU_1000_ACOES", vPrecoPor1Ou1000Acoes); stmtDestino.setBigDecimalAtName("PERC_PROVENTO_POR_PRECO", vProventoPorPreco); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } } } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha + 1; problemaDetalhado.colunaProblematicaDoArquivo = nomeDaColuna; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } Code Sample 2: private NodeList getNodeListForDataFile(String fileName, String dataType) { NodeList list = null; try { URL url = new URL(WEBSITE_PROTOCAL, WEBSITE_HOST, "/" + fileName + ".xml"); InputStream is = url.openStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.parse(is); list = document.getElementsByTagName(dataType); } catch (SAXException e) { log.error("Error reading " + dataType + " data", e); } catch (IOException e) { log.error("Error reading " + dataType + " data", e); } catch (ParserConfigurationException e) { log.error("Error reading " + dataType + " data", e); } return list; }
00
Code Sample 1: public void testTransactions0010() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0010 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i + ((j - 1) * rowsToAdd)); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) { i -= rowsToAdd; } assertEquals(rs.getString(1).trim().length(), i); } assertEquals(count, (2 * rowsToAdd)); stmt.close(); pstmt.close(); con.setAutoCommit(true); } Code Sample 2: public I18N(JApplet applet) { if (prop != null) { return; } String lang = "de"; try { Properties userProperties = new Properties(); if (applet != null) { URL url = new URL(applet.getCodeBase() + xConfigPath + "ElementDesigner.cfg"); userProperties.load(url.openStream()); } else { userProperties.load(new FileInputStream(xConfigPath + "ElementDesigner.cfg")); } if (userProperties.containsKey("language")) { lang = userProperties.getProperty("language"); } } catch (Exception ex) { ex.printStackTrace(); } prop = new Properties(); try { if (applet != null) { URL url = new URL(applet.getCodeBase() + xLanguagePath + lang + ".ini"); prop.load(url.openStream()); } else { prop.load(new FileInputStream(xLanguagePath + lang + ".ini")); } } catch (Exception ex) { ex.printStackTrace(); try { if (applet != null) { URL url = new URL(applet.getCodeBase() + xLanguagePath + "de.ini"); prop.load(url.openStream()); } else { prop.load(new FileInputStream(xLanguagePath + "de.ini")); } } catch (Exception ex2) { JOptionPane.showMessageDialog(null, "Language file languages/de.ini not found.\nPlease run the program from its directory."); System.exit(5); } } }
00
Code Sample 1: public static String getURLContent(String urlStr) throws MalformedURLException, IOException { URL url = new URL(urlStr); log.info("url: " + url); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer buf = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } in.close(); return buf.toString(); } 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 ODFSignatureService(TimeStampServiceValidator timeStampServiceValidator, RevocationDataService revocationDataService, SignatureFacet signatureFacet, InputStream documentInputStream, OutputStream documentOutputStream, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo digestAlgo) throws Exception { super(digestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".odf"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: private CharBuffer decodeToFile(ReplayInputStream inStream, String backingFilename, String encoding) throws IOException { CharBuffer charBuffer = null; BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, encoding)); File backingFile = new File(backingFilename); this.decodedFile = File.createTempFile(backingFile.getName(), WRITE_ENCODING, backingFile.getParentFile()); FileOutputStream fos; fos = new FileOutputStream(this.decodedFile); IOUtils.copy(reader, fos, WRITE_ENCODING); fos.close(); charBuffer = getReadOnlyMemoryMappedBuffer(this.decodedFile).asCharBuffer(); return charBuffer; } Code Sample 2: private void preprocessImages(GeoImage[] detailedImages) throws IOException { for (int i = 0; i < detailedImages.length; i++) { BufferedImage img = loadImage(detailedImages[i].getPath()); detailedImages[i].setLatDim(img.getHeight()); detailedImages[i].setLonDim(img.getWidth()); freeImage(img); String fileName = detailedImages[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("filename " + tmp); File worldFile = new File(tmp); if (!worldFile.exists()) { System.out.println("Rez: Could not find file: " + tmp); debug("Rez: Could not find directory: " + tmp); throw new IOException("File not Found"); } BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLonSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLonExtent(detailedImages[i].getLonSpacing() * ((double) detailedImages[i].getLonDim() - 1d)); System.out.println("setLonExtent " + detailedImages[i].getLonExtent()); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLatSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLatExtent(detailedImages[i].getLatSpacing() * ((double) detailedImages[i].getLatDim() - 1d)); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); detailedImages[i].setPath(tmp); DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } else { System.out.println("Rez: ERROR: World file for image is null"); } } }
11
Code Sample 1: public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } } Code Sample 2: public InputStream resolve(String uri) throws SAJException { try { URI url = new URI(uri); InputStream stream = url.toURL().openStream(); if (stream == null) throw new SAJException("URI " + uri + " can't be resolved"); return stream; } catch (SAJException e) { throw e; } catch (Exception e) { throw new SAJException("Invalid uri to resolve " + uri, e); } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; }
00
Code Sample 1: 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 static void _readAllRegionMDFiles(ClassLoader loader, RegionMetadata bean, String regionMDFile) { if (_LOG.isFinest()) { _LOG.finest("searching for region-metadata with resource:{0}", regionMDFile); } try { Enumeration<URL> files = loader.getResources(regionMDFile); while (files.hasMoreElements()) { URL url = files.nextElement(); String publicId = url.toString(); try { InputStream in = url.openStream(); _readRegionMetadata(bean, in, publicId); in.close(); } catch (IOException e) { _error(publicId, e); } } } catch (IOException e) { _LOG.warning("ERR_GET_REGION_METADATA_FILE", __CONFIG_FILE_OTHER); _LOG.warning(e); } }
11
Code Sample 1: private void parseExternalCss(Document d) throws XPathExpressionException, IOException { InputStream is = null; try { XPath xp = xpf.newXPath(); XPathExpression xpe = xp.compile("//link[@type='text/css']/@href"); NodeList nl = (NodeList) xpe.evaluate(d, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Attr a = (Attr) nl.item(i); String url = a.getValue(); URL u = new URL(url); is = new BufferedInputStream(u.openStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); parser.add(new String(baos.toByteArray(), "UTF-8")); Element linkNode = a.getOwnerElement(); Element parent = (Element) linkNode.getParentNode(); parent.removeChild(linkNode); IOUtils.closeQuietly(is); is = null; } } finally { IOUtils.closeQuietly(is); } } 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 { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: protected void setupService(MessageContext msgContext) throws Exception { String realpath = msgContext.getStrProp(Constants.MC_REALPATH); String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION); if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION; if ((realpath != null) && (realpath.endsWith(extension))) { String jwsFile = realpath; String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); File f2 = new File(jwsFile); if (!f2.exists()) { throw new FileNotFoundException(rel); } if (rel.charAt(0) == '/') { rel = rel.substring(1); } int lastSlash = rel.lastIndexOf('/'); String dir = null; if (lastSlash > 0) { dir = rel.substring(0, lastSlash); } String file = rel.substring(lastSlash + 1); String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR); if (outdir == null) outdir = "."; if (dir != null) { outdir = outdir + File.separator + dir; } File outDirectory = new File(outdir); if (!outDirectory.exists()) { outDirectory.mkdirs(); } if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile); String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "java"; String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "class"; if (log.isDebugEnabled()) { log.debug("jFile: " + jFile); log.debug("cFile: " + cFile); log.debug("outdir: " + outdir); } File f1 = new File(cFile); String clsName = null; if (clsName == null) clsName = f2.getName(); if (clsName != null && clsName.charAt(0) == '/') clsName = clsName.substring(1); clsName = clsName.substring(0, clsName.length() - extension.length()); clsName = clsName.replace('/', '.'); if (log.isDebugEnabled()) log.debug("ClsName: " + clsName); if (!f1.exists() || f2.lastModified() > f1.lastModified()) { log.debug(Messages.getMessage("compiling00", jwsFile)); log.debug(Messages.getMessage("copy00", jwsFile, jFile)); FileReader fr = new FileReader(jwsFile); FileWriter fw = new FileWriter(jFile); char[] buf = new char[4096]; int rc; while ((rc = fr.read(buf, 0, 4095)) >= 0) fw.write(buf, 0, rc); fw.close(); fr.close(); log.debug("javac " + jFile); Compiler compiler = CompilerFactory.getCompiler(); compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext)); compiler.setDestination(outdir); compiler.addFile(jFile); boolean result = compiler.compile(); (new File(jFile)).delete(); if (!result) { (new File(cFile)).delete(); Document doc = XMLUtils.newDocument(); Element root = doc.createElementNS("", "Errors"); StringBuffer message = new StringBuffer("Error compiling "); message.append(jFile); message.append(":\n"); List errors = compiler.getErrors(); int count = errors.size(); for (int i = 0; i < count; i++) { CompilerError error = (CompilerError) errors.get(i); if (i > 0) message.append("\n"); message.append("Line "); message.append(error.getStartLine()); message.append(", column "); message.append(error.getStartColumn()); message.append(": "); message.append(error.getMessage()); } root.appendChild(doc.createTextNode(message.toString())); throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root }); } ClassUtils.removeClassLoader(clsName); soapServices.remove(clsName); } ClassLoader cl = ClassUtils.getClassLoader(clsName); if (cl == null) { cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile); } msgContext.setClassLoader(cl); SOAPService rpc = (SOAPService) soapServices.get(clsName); if (rpc == null) { rpc = new SOAPService(new RPCProvider()); rpc.setName(clsName); rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName); rpc.setEngine(msgContext.getAxisEngine()); String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS); if (allowed == null) allowed = "*"; rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed); String scope = (String) getOption(RPCProvider.OPTION_SCOPE); if (scope == null) scope = Scope.DEFAULT.getName(); rpc.setOption(RPCProvider.OPTION_SCOPE, scope); rpc.getInitializedServiceDesc(msgContext); soapServices.put(clsName, rpc); } rpc.setEngine(msgContext.getAxisEngine()); rpc.init(); msgContext.setService(rpc); } if (log.isDebugEnabled()) { log.debug("Exit: JWSHandler::invoke"); } }
00
Code Sample 1: private void readFromObjectInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); ObjectInput input = new ObjectInputStream(stream); fDrawing.release(); fDrawing = (Drawing) input.readObject(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error: " + e); } catch (ClassNotFoundException e) { initDrawing(); showStatus("Class not found: " + e); } } Code Sample 2: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
11
Code Sample 1: protected String contentString() { String result = null; URL url; String encoding = null; try { url = url(); URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); for (Enumeration e = bindingKeys().objectEnumerator(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("?")) { connection.setRequestProperty(key.substring(1), valueForBinding(key).toString()); } } if (connection.getContentEncoding() != null) { encoding = connection.getContentEncoding(); } if (encoding == null) { encoding = (String) valueForBinding("encoding"); } if (encoding == null) { encoding = "UTF-8"; } InputStream stream = connection.getInputStream(); byte bytes[] = ERXFileUtilities.bytesFromInputStream(stream); stream.close(); result = new String(bytes, encoding); } catch (IOException ex) { throw NSForwardException._runtimeExceptionForThrowable(ex); } return result; } Code Sample 2: private void triggerBuild(Properties props, String project, int rev) throws IOException { boolean doBld = Boolean.parseBoolean(props.getProperty(project + ".bld")); String url = props.getProperty(project + ".url"); if (!doBld || project == null || project.length() == 0) { System.out.println("BuildLauncher: Not configured to build '" + project + "'"); return; } else if (url == null) { throw new IOException("Tried to launch build for project '" + project + "' but " + project + ".url property is not defined!"); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); System.out.println(fmt.format(new Date()) + ": Triggering a build via: " + url); BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while (r.readLine() != null) ; System.out.println(fmt.format(new Date()) + ": Build triggered!"); LATEST_BUILD.put(project, rev); r.close(); System.out.println(fmt.format(new Date()) + ": triggerBuild() done!"); }
11
Code Sample 1: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; } Code Sample 2: public static String getUserPass(String user) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(user.getBytes()); byte[] hash = digest.digest(); System.out.println("Returning user pass:" + hash); return hash.toString(); }
00
Code Sample 1: private void validateODFDoc(String url, String ver, ValidationReport commentary) throws IOException, MalformedURLException { logger.debug("Beginning document validation ..."); synchronized (ODFValidationSession.class) { PropertyMapBuilder builder = new PropertyMapBuilder(); String[] segments = url.split("/"); CommentatingErrorHandler h = new CommentatingErrorHandler(commentary, segments[segments.length - 1]); ValidateProperty.ERROR_HANDLER.put(builder, h); ValidationDriver driver = new ValidationDriver(builder.toPropertyMap()); InputStream candidateStream = null; try { logger.debug("Loading schema version " + ver); byte[] schemaBytes = getSchemaForVersion(ver); driver.loadSchema(new InputSource(new ByteArrayInputStream(schemaBytes))); URLConnection conn = new URL(url).openConnection(); candidateStream = conn.getInputStream(); logger.debug("Calling validate()"); commentary.incIndent(); boolean isValid = driver.validate(new InputSource(candidateStream)); logger.debug("Errors in instance:" + h.getInstanceErrCount()); if (h.getInstanceErrCount() > CommentatingErrorHandler.THRESHOLD) { commentary.addComment("(<i>" + (h.getInstanceErrCount() - CommentatingErrorHandler.THRESHOLD) + " error(s) omitted for the sake of brevity</i>)"); } commentary.decIndent(); if (isValid) { commentary.addComment("The document is valid"); } else { commentary.addComment("ERROR", "The document is invalid"); } } catch (SAXException e) { commentary.addComment("FATAL", "The resource is not conformant XML: " + e.getMessage()); logger.error(e.getMessage()); } finally { Utils.streamClose(candidateStream); } } } Code Sample 2: @Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } Code Sample 2: private String[] verifyConnection(Socket clientConnection) throws Exception { List<String> requestLines = new ArrayList<String>(); InputStream is = clientConnection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringTokenizer st = new StringTokenizer(in.readLine()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no method token in this connection"); } String method = st.nextToken(); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no URI token in this connection"); } String uri = decodePercent(st.nextToken()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no version token in this connection"); } String version = st.nextToken(); Properties parms = new Properties(); int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } String params = ""; if (parms.size() > 0) { params = "?"; for (Object key : parms.keySet()) { params = params + key + "=" + parms.getProperty(((String) key)) + "&"; } params = params.substring(0, params.length() - 1).replace(" ", "%20"); } logger.debug("HTTP Request: " + method + " " + uri + params + " " + version); requestLines.add(method + " " + uri + params + " " + version); Properties headerVars = new Properties(); String line; String currentBoundary = null; Stack<String> boundaryStack = new Stack<String>(); boolean readingBoundary = false; String additionalData = ""; while (in.ready() && (line = in.readLine()) != null) { if (line.equals("") && (headerVars.get("Content-Type") == null || headerVars.get("Content-Length") == null)) { break; } logger.debug("HTTP Request Header: " + line); if (line.contains(": ")) { String vals[] = line.split(": "); headerVars.put(vals[0].trim(), vals[1].trim()); } if (!readingBoundary && line.contains(": ")) { if (line.contains("boundary=")) { currentBoundary = line.split("boundary=")[1].trim(); boundaryStack.push("--" + currentBoundary); } continue; } else if (line.equals("") && boundaryStack.isEmpty()) { int val = Integer.parseInt((String) headerVars.get("Content-Length")); if (headerVars.getProperty("Content-Type").contains("x-www-form-urlencoded")) { char buf[] = new char[val]; int read = in.read(buf); line = String.valueOf(buf, 0, read); additionalData = line; logger.debug("HTTP Request Header Form Parameters: " + line); } } else if (line.equals(boundaryStack.peek()) && !readingBoundary) { readingBoundary = true; } else if (line.equals(boundaryStack.peek()) && readingBoundary) { readingBoundary = false; } else if (line.contains(": ") && readingBoundary) { if (method.equalsIgnoreCase("PUT")) { if (line.contains("form-data; ")) { String formValues = line.split("form-data; ")[1]; for (String varValue : formValues.replace("\"", "").split("; ")) { String[] vV = varValue.split("="); vV[0] = decodePercent(vV[0]); vV[1] = decodePercent(vV[1]); headerVars.put(vV[0], vV[1]); } } } } else if (line.contains("") && readingBoundary && !boundaryStack.isEmpty() && headerVars.get("filename") != null) { int length = Integer.parseInt(headerVars.getProperty("Content-Length")); if (headerVars.getProperty("Content-Transfer-Encoding").contains("binary")) { File uploadFilePath = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory")); if (!uploadFilePath.exists()) { logger.error("Temporaty dir does not exist: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.isDirectory()) { logger.error("Temporary dir is not a directory: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.canWrite()) { logger.error("VOctopus Webserver doesn't have permissions to write on temporary dir: " + uploadFilePath.getCanonicalPath()); } FileOutputStream out = null; try { String putUploadPath = uploadFilePath.getAbsolutePath() + "/" + headerVars.getProperty("filename"); out = new FileOutputStream(putUploadPath); OutputStream outf = new BufferedOutputStream(out); int c; while (in.ready() && (c = in.read()) != -1 && length-- > 0) { outf.write(c); } } finally { if (out != null) { out.close(); } } File copied = new File(VOctopusConfigurationManager.getInstance().getDocumentRootPath() + uri + headerVars.get("filename")); File tempFile = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory") + "/" + headerVars.get("filename")); FileChannel ic = new FileInputStream(tempFile.getAbsolutePath()).getChannel(); FileChannel oc = new FileOutputStream(copied.getAbsolutePath()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } } } for (Object var : headerVars.keySet()) { requestLines.add(var + ": " + headerVars.get(var)); } if (!additionalData.equals("")) { requestLines.add("ADDITIONAL" + additionalData); } return requestLines.toArray(new String[requestLines.size()]); }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static String encrypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } return hexString.toString(); }
00
Code Sample 1: public static URL[] getURLsForAllJars(URL url, File tmpDir) { FileInputStream fin = null; InputStream in = null; ZipInputStream zin = null; try { ArrayList array = new ArrayList(); in = url.openStream(); String fileName = url.getFile(); int index = fileName.lastIndexOf('/'); if (index != -1) { fileName = fileName.substring(index + 1); } final File f = createTempFile(fileName, in, tmpDir); fin = (FileInputStream) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream(f); } }); array.add(f.toURL()); zin = new ZipInputStream(fin); ZipEntry entry; String entryName; while ((entry = zin.getNextEntry()) != null) { entryName = entry.getName(); if ((entryName != null) && entryName.toLowerCase().startsWith("lib/") && entryName.toLowerCase().endsWith(".jar")) { String suffix = entryName.substring(4); File f2 = createTempFile(suffix, zin, tmpDir); array.add(f2.toURL()); } } return (URL[]) array.toArray(new URL[array.size()]); } catch (Exception e) { throw new RuntimeException(e); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (zin != null) { try { zin.close(); } catch (IOException e) { } } } } Code Sample 2: @Test @Ignore public void testToJson() throws IOException { JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper()); BulkOperation op = js.createBulkOperation(createTestData(10000), false); IOUtils.copy(op.getData(), System.out); }
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: @Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
11
Code Sample 1: public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); } Code Sample 2: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public boolean delwuliao(String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("delete from addwuliao where pid=?"); pm.setString(1, pid); int x = pm.executeUpdate(); if (x == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; } Code Sample 2: @Override public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { URL baseUrl = this.baseUrl; if (this.baseUrl == null) { baseUrl = url; } InputStream in; try { in = url.openStream(); } catch (IOException ex) { throw new FileNotFoundException("Can't read " + url); } return load(new BufferedInputStream(in), baseUrl); }
00
Code Sample 1: public static void compressAll(File dir, File file) throws IOException { if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.setLevel(0); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytesRead; for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); } Code Sample 2: public static String checkPublicIP() { String ipAddress = null; try { URL url; url = new URL("http://checkip.dyndns.org/"); InputStreamReader in = new InputStreamReader(url.openStream()); BufferedReader buffer = new BufferedReader(in); String line; Pattern p = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"); while ((line = buffer.readLine()) != null) { if (line.indexOf("IP Address:") != -1) { Matcher m = p.matcher(line); if (m.find()) { ipAddress = m.group(); break; } } } buffer.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ipAddress; }
00
Code Sample 1: @Override public void run() { try { if (!Util.isSufficienDataForUpload(recordedGeoPoints)) return; final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes()); final HttpClient httpClient = new DefaultHttpClient(); final HttpPost request = new HttpPost(UPLOADSCRIPT_URL); final MultipartEntity requestEntity = new MultipartEntity(); requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx")); httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false); request.setEntity(requestEntity); final HttpResponse response = httpClient.execute(request); final int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { logger.error("GPXUploader", "status != HttpStatus.SC_OK"); } else { final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent())); final char[] buf = new char[8 * 1024]; int read; final StringBuilder sb = new StringBuilder(); while ((read = r.read(buf)) != -1) sb.append(buf, 0, read); logger.debug("GPXUploader", "Response: " + sb.toString()); } } catch (final Exception e) { } } Code Sample 2: public static void writeToFile(InputStream input, File file, ProgressListener listener, long length) { OutputStream output = null; try { output = new CountingOutputStream(new FileOutputStream(file), listener, length); IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
11
Code Sample 1: public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public static String doPostWithBasicAuthentication(URL url, String username, String password, String parameters, Map<String, String> headers) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(2000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (parameters != null) con.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } Code Sample 2: void loadSVG(String svgFileURL) { try { URL url = new URL(svgFileURL); URLConnection c = url.openConnection(); c.setRequestProperty("Accept-Encoding", "gzip"); InputStream is = c.getInputStream(); String encoding = c.getContentEncoding(); if ("gzip".equals(encoding) || "x-gzip".equals(encoding) || svgFileURL.toLowerCase().endsWith(".svgz")) { is = new GZIPInputStream(is); } is = new BufferedInputStream(is); Document svgDoc = AppletUtils.parse(is, false); if (svgDoc != null) { if (grMngr.mainView.isBlank() == null) { grMngr.mainView.setBlank(cfgMngr.backgroundColor); } SVGReader.load(svgDoc, grMngr.mSpace, true, svgFileURL); grMngr.seekBoundingBox(); grMngr.buildLogicalStructure(); ConfigManager.defaultFont = VText.getMainFont(); grMngr.reveal(); if (grMngr.previousLocations.size() == 1) { grMngr.previousLocations.removeElementAt(0); } if (grMngr.rView != null) { grMngr.rView.getGlobalView(grMngr.mSpace.getCamera(1), 100); } grMngr.cameraMoved(null, null, 0); } else { System.err.println("An error occured while loading file " + svgFileURL); } } catch (Exception ex) { grMngr.reveal(); ex.printStackTrace(); } }
11
Code Sample 1: @Override public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { String userAgentGroup = processUserAgent(request); final LiwenxRequest lRequest = new LiwenxRequestImpl(request, response, messageSource, userAgentGroup); Locator loc = router.route(lRequest); if (loc instanceof RedirectLocator) { response.sendRedirect(((RedirectLocator) loc).getPage()); } else { ((AbstractLiwenxRequest) lRequest).setRequestedLocator(loc); try { LiwenxResponse resp = processPage(lRequest, lRequest.getRequestedLocator(), maxRedirections); processHeaders(resp, response); processCookies(resp, response); if (resp instanceof ExternalRedirectionResponse) { response.sendRedirect(((ExternalRedirectionResponse) resp).getRedirectTo()); } else if (resp instanceof BinaryResponse) { BinaryResponse bResp = (BinaryResponse) resp; response.setContentType(bResp.getMimeType().toString()); IOUtils.copy(bResp.getInputStream(), response.getOutputStream()); } else if (resp instanceof XmlResponse) { final Element root = ((XmlResponse) resp).getXml(); Document doc = root.getDocument(); if (doc == null) { doc = new Document(root); } final Locator l = lRequest.getCurrentLocator(); final Device device = l.getDevice(); response.setContentType(calculateContentType(device)); response.setCharacterEncoding(encoding); if (device == Device.HTML) { view.processView(doc, l.getLocale(), userAgentGroup, response.getWriter()); } else { Serializer s = new Serializer(response.getOutputStream(), encoding); s.write(doc); } } } catch (PageNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (TooManyRedirectionsException e) { throw e; } catch (Exception e) { throw e; } } } Code Sample 2: public static void TestDBStore() throws PDException, Exception { StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB"); System.out.println("Driver[" + StDB.getDriver() + "] Tabla [" + StDB.getTable() + "]"); StDB.Connect(); FileInputStream in = new FileInputStream("/tmp/readme.htm"); StDB.Insert("12345678-1", "1.0", in); int TAMBUFF = 1024 * 64; byte Buffer[] = new byte[TAMBUFF]; InputStream Bytes; Bytes = StDB.Retrieve("12345678-1", "1.0"); FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm"); int readed = Bytes.read(Buffer); while (readed != -1) { fo.write(Buffer, 0, readed); readed = Bytes.read(Buffer); } Bytes.close(); fo.close(); StDB.Delete("12345678-1", "1.0"); StDB.Disconnect(); }
11
Code Sample 1: private void loadObject(URL url) throws IOException { InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); int linecounter = 0; try { String line; boolean firstpass = true; String[] coordstext; Material material = null; while (((line = br.readLine()) != null)) { linecounter++; line = line.trim(); if (line.length() > 0) { if (line.startsWith("mtllib")) { String mtlfile = line.substring(6).trim(); loadMtlFile(new URL(url, mtlfile)); } else if (line.startsWith("usemtl")) { String mtlname = line.substring(6).trim(); material = (Material) materials.get(mtlname); } else if (line.charAt(0) == 'v' && line.charAt(1) == ' ') { float[] coords = new float[4]; coordstext = line.split("\\s+"); for (int i = 1; i < coordstext.length; i++) { coords[i - 1] = Float.valueOf(coordstext[i]).floatValue(); } if (firstpass) { rightpoint = coords[0]; leftpoint = coords[0]; toppoint = coords[1]; bottompoint = coords[1]; nearpoint = coords[2]; farpoint = coords[2]; firstpass = false; } if (coords[0] > rightpoint) { rightpoint = coords[0]; } if (coords[0] < leftpoint) { leftpoint = coords[0]; } if (coords[1] > toppoint) { toppoint = coords[1]; } if (coords[1] < bottompoint) { bottompoint = coords[1]; } if (coords[2] > nearpoint) { nearpoint = coords[2]; } if (coords[2] < farpoint) { farpoint = coords[2]; } vertexsets.add(coords); } else if (line.charAt(0) == 'v' && line.charAt(1) == 't') { float[] coords = new float[4]; coordstext = line.split("\\s+"); for (int i = 1; i < coordstext.length; i++) { coords[i - 1] = Float.valueOf(coordstext[i]).floatValue(); } vertexsetstexs.add(coords); } else if (line.charAt(0) == 'v' && line.charAt(1) == 'n') { float[] coords = new float[4]; coordstext = line.split("\\s+"); for (int i = 1; i < coordstext.length; i++) { coords[i - 1] = Float.valueOf(coordstext[i]).floatValue(); } vertexsetsnorms.add(coords); } else if (line.charAt(0) == 'f' && line.charAt(1) == ' ') { coordstext = line.split("\\s+"); int[] v = new int[coordstext.length - 1]; int[] vt = new int[coordstext.length - 1]; int[] vn = new int[coordstext.length - 1]; for (int i = 1; i < coordstext.length; i++) { String fixstring = coordstext[i].replaceAll("//", "/0/"); String[] tempstring = fixstring.split("/"); v[i - 1] = Integer.valueOf(tempstring[0]).intValue(); if (tempstring.length > 1) { vt[i - 1] = Integer.valueOf(tempstring[1]).intValue(); } else { vt[i - 1] = 0; } if (tempstring.length > 2) { vn[i - 1] = Integer.valueOf(tempstring[2]).intValue(); } else { vn[i - 1] = 0; } } Face face = new Face(v, vt, vn, material); faces.add(face); } } } } catch (IOException e) { System.out.println("Failed to read file: " + br.toString()); } catch (NumberFormatException e) { System.out.println("Malformed OBJ (on line " + linecounter + "): " + br.toString() + "\r \r" + e.getMessage()); } } Code Sample 2: public String get(String s) { s = s.replaceAll("[^a-z0-9_]", ""); StringBuilder sb = new StringBuilder(); try { String result = null; URL url = new URL("http://docs.google.com/Doc?id=" + URLEncoder.encode(s, "UTF-8")); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; int state = 0; while ((inputLine = in.readLine()) != null) { if (state == 0) { int textPos = inputLine.indexOf("id=\"doc-contents"); if (textPos >= 0) { state = 1; } } else if (state == 1) { int textPos = inputLine.indexOf("</div>"); if (textPos >= 0) break; inputLine = inputLine.replaceAll("[\\u0000-\\u001F]", ""); sb.append(inputLine); } } in.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
11
Code Sample 1: public LinkedList<NameValuePair> getScoreboard() { InputStream is = null; String result = ""; LinkedList<NameValuePair> scores = new LinkedList<NameValuePair>(); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return null; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json = new JSONObject(result); JSONArray data = json.getJSONArray("data"); JSONArray me = json.getJSONArray("me"); for (int i = 0; i < data.length(); i++) { JSONObject single = data.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } for (int i = 0; i < me.length(); i++) { JSONObject single = me.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } System.out.println(json); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return scores; } Code Sample 2: public static String loadResource(String resource) { URL url = ClassLoader.getSystemResource("resources/" + resource); StringBuffer buffer = new StringBuffer(); if (url == null) { ErrorMessage.handle(new NullPointerException("URL for resources/" + resource + " not found")); } else { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } } return buffer.toString(); }
11
Code Sample 1: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); } Code Sample 2: public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
00
Code Sample 1: public static void BubbleSortLong1(long[] num) { boolean flag = true; // set flag to true to begin first pass long temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } } Code Sample 2: public void run() { logger.info("downloading '" + url.toString() + "' to: " + dstFile.getAbsolutePath()); Preferences prefs = Preferences.userRoot().node("gvsig.downloader"); int timeout = prefs.getInt("timeout", 60000); DataOutputStream dos; try { DataInputStream is; OutputStreamWriter os = null; HttpURLConnection connection = null; if (url.getProtocol().equals("https")) { disableHttsValidation(); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(timeout); if (data != null) { connection.setRequestProperty("SOAPAction", "post"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); os = new OutputStreamWriter(connection.getOutputStream()); os.write(data); os.flush(); is = new DataInputStream(connection.getInputStream()); } else { is = new DataInputStream(url.openStream()); } dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dstFile))); byte[] buffer = new byte[1024 * 4]; long readed = 0; for (int i = is.read(buffer); !Utilities.getCanceled(groupID) && i > 0; i = is.read(buffer)) { dos.write(buffer, 0, i); readed += i; } if (os != null) { os.close(); } dos.close(); is.close(); is = null; dos = null; if (Utilities.getCanceled(groupID)) { logger.warning("[RemoteServices] '" + url + "' CANCELED."); dstFile.delete(); dstFile = null; } else { Utilities.addDownloadedURL(url, dstFile.getAbsolutePath()); } } catch (Exception e) { e.printStackTrace(); Utilities.downloadException = e; } }
00
Code Sample 1: protected List webservice(URL url, List locations, boolean followRedirect) throws GeoServiceException { long start = System.currentTimeMillis(); int rowCount = 0, hitCount = 0; try { HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); try { con.getClass().getMethod("setConnectTimeout", new Class[] { Integer.TYPE }).invoke(con, new Object[] { TIMEOUT }); } catch (Throwable t) { LOG.info("can't set connection timeout"); } con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); Writer out = new OutputStreamWriter(con.getOutputStream(), UTF8); out.write(HEADER + "\n"); for (int i = 0; i < locations.size(); i++) { if (i > 0) out.write("\n"); out.write(encode((GeoLocation) locations.get(i))); } out.close(); } catch (IOException e) { throw new GeoServiceException("Accessing GEO Webservice failed", e); } List rows = new ArrayList(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), UTF8)); for (int l = 0; l < locations.size(); l++) { String line = in.readLine(); LOG.finer(line); if (line == null) break; if (l == 0 && followRedirect) { try { return webservice(new URL(line), locations, false); } catch (MalformedURLException e) { } } rowCount++; List row = new ArrayList(); if (!line.startsWith("?")) { StringTokenizer hits = new StringTokenizer(line, ";"); while (hits.hasMoreTokens()) { GeoLocation hit = decode(hits.nextToken()); if (hit != null) { row.add(hit); hitCount++; } } } rows.add(row); } in.close(); } catch (IOException e) { throw new GeoServiceException("Reading from GEO Webservice failed", e); } if (rows.size() < locations.size()) throw new GeoServiceException("GEO Webservice returned " + rows.size() + " rows for " + locations.size() + " locations"); return rows; } finally { long secs = (System.currentTimeMillis() - start) / 1000; LOG.fine("query for " + locations.size() + " locations in " + secs + "s resulted in " + rowCount + " rows and " + hitCount + " total hits"); } } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: public void patchFile(final File classFile) { if (!classFile.exists()) { myErrors.add(new FormErrorInfo(null, "Class to bind does not exist: " + myRootContainer.getClassToBind())); return; } FileInputStream fis; try { byte[] patchedData; fis = new FileInputStream(classFile); try { patchedData = patchClass(fis); if (patchedData == null) { return; } } finally { fis.close(); } FileOutputStream fos = new FileOutputStream(classFile); try { fos.write(patchedData); } finally { fos.close(); } } catch (IOException e) { myErrors.add(new FormErrorInfo(null, "Cannot read or write class file " + classFile.getPath() + ": " + e.toString())); } } Code Sample 2: private void processHelpFile() { InputStream in = null; if (line.hasOption("helpfile")) { OutputStream out = null; try { String filename = line.getOptionValue("helpfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); baseProperties.setProperty("helpfile", filename); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return; } Properties props = new Properties(baseProperties); ClassLoader cl = this.getClass().getClassLoader(); Document doc = null; try { in = cl.getResourceAsStream(RESOURCE_PKG + "/help-doc.xml"); doc = XmlUtils.parse(in); } catch (XmlException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } transformResource(doc, "help-doc.xsl", props, "help-doc.html"); baseProperties.setProperty("helpfile", "help-doc.html"); }
00
Code Sample 1: public IntactOntology parseOboFile(URL url, boolean keepTemporaryFile) throws PsiLoaderException { if (url == null) { throw new IllegalArgumentException("Please give a non null URL."); } StringBuffer buffer = new StringBuffer(1024 * 8); try { System.out.println("Loading URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()), 1024); String line; int lineCount = 0; while ((line = in.readLine()) != null) { lineCount++; buffer.append(line).append(NEW_LINE); if ((lineCount % 20) == 0) { System.out.print("."); System.out.flush(); if ((lineCount % 500) == 0) { System.out.println(" " + lineCount); } } } in.close(); File tempDirectory = new File(System.getProperty("java.io.tmpdir", "tmp")); if (!tempDirectory.exists()) { if (!tempDirectory.mkdirs()) { throw new IOException("Cannot create temp directory: " + tempDirectory.getAbsolutePath()); } } System.out.println("Using temp directory: " + tempDirectory.getAbsolutePath()); File tempFile = File.createTempFile("psimi.v25.", ".obo", tempDirectory); tempFile.deleteOnExit(); tempFile.deleteOnExit(); System.out.println("The OBO file is temporary store as: " + tempFile.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(tempFile), 1024); out.write(buffer.toString()); out.flush(); out.close(); return parseOboFile(tempFile); } catch (IOException e) { throw new PsiLoaderException("Error while loading URL (" + url + ")", e); } } Code Sample 2: public void download(String contentUuid, File path) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream output = new FileOutputStream(path); IoUtils.copyBytes(inputStream, output); IoUtils.close(inputStream); IoUtils.close(output); } catch (IOException ioex) { throw new WebServiceClientException("Could not download or saving content to path [" + path.getAbsolutePath() + "]", ioex); } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } }
11
Code Sample 1: public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); } Code Sample 2: public static String generate(String username, String password) throws PersistenceException { String output = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(username.getBytes()); md.update(password.getBytes()); byte[] rawhash = md.digest(); output = byteToBase64(rawhash); } catch (Exception e) { throw new PersistenceException("error, could not generate password"); } return output; }
11
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static String[] listFilesInJar(String resourcesLstName, String dirPath, String ext) { try { dirPath = Tools.subString(dirPath, "\\", "/"); if (!dirPath.endsWith("/")) { dirPath = dirPath + "/"; } if (dirPath.startsWith("/")) { dirPath = dirPath.substring(1, dirPath.length()); } URL url = ResourceLookup.getClassResourceUrl(Tools.class, resourcesLstName); if (url == null) { String msg = "File not found " + resourcesLstName; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } InputStream is = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String name = in.readLine(); HashSet<String> list = new HashSet<String>(10); while (name != null) { name = in.readLine(); if (name == null) { continue; } if (ext != null && !name.endsWith(ext)) { continue; } if (name.indexOf('.') == -1 && !name.endsWith("/")) { name = name + "/"; } int index = name.indexOf(dirPath); if (index < 0) { continue; } index += dirPath.length(); if (index >= name.length() - 1) { continue; } index = name.indexOf("/", index); if (ext != null && (name.endsWith("/") || index >= 0)) { continue; } else if (ext == null && (index < 0 || index < name.length() - 1)) { continue; } list.add("/" + name); } is.close(); String[] toReturn = {}; return list.toArray(toReturn); } catch (IOException ioe) { String msg = "Error reading file " + resourcesLstName + " caused by " + ioe; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } }
11
Code Sample 1: public void init(File file) { InputStream is = null; ByteArrayOutputStream os = null; try { is = new FileInputStream(file); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); } catch (Throwable e) { throw new VisualizerEngineException("Unexcpected exception while reading MDF file", e); } if (simulationEngine != null) simulationEngine.stopSimulation(); simulationEngine = new TrafficAsynchSimulationEngine(); simulationEngine.init(MDFReader.read(os.toByteArray())); simulationEngineThread = null; } Code Sample 2: private 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(); } }
11
Code Sample 1: public void setFlag(Flags.Flag oFlg, boolean bFlg) throws MessagingException { String sColunm; super.setFlag(oFlg, bFlg); if (oFlg.equals(Flags.Flag.ANSWERED)) sColunm = DB.bo_answered; else if (oFlg.equals(Flags.Flag.DELETED)) sColunm = DB.bo_deleted; else if (oFlg.equals(Flags.Flag.DRAFT)) sColunm = DB.bo_draft; else if (oFlg.equals(Flags.Flag.FLAGGED)) sColunm = DB.bo_flagged; else if (oFlg.equals(Flags.Flag.RECENT)) sColunm = DB.bo_recent; else if (oFlg.equals(Flags.Flag.SEEN)) sColunm = DB.bo_seen; else sColunm = null; if (null != sColunm && oFolder instanceof DBFolder) { JDCConnection oConn = null; PreparedStatement oUpdt = null; try { oConn = ((DBFolder) oFolder).getConnection(); String sSQL = "UPDATE " + DB.k_mime_msgs + " SET " + sColunm + "=" + (bFlg ? "1" : "0") + " WHERE " + DB.gu_mimemsg + "='" + getMessageGuid() + "'"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); oUpdt = oConn.prepareStatement(sSQL); oUpdt.executeUpdate(); oUpdt.close(); oUpdt = null; oConn.commit(); oConn = null; } catch (SQLException e) { if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } if (null != oUpdt) { try { oUpdt.close(); } catch (Exception ignore) { } } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(e.getMessage(), e); } } } Code Sample 2: public Atividade insertAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade (idatividade, requerente_idrequerente, datacriacao, datatermino, valor, tipoatividade, descricao, fase_idfase, estado) " + "values " + "(nextval('seq_atividade'), " + atividade.getRequerente().getIdRequerente() + ", " + "'" + atividade.getDataCriacao() + "', '" + atividade.getDataTermino() + "', '" + atividade.getValor() + "', '" + atividade.getTipoAtividade().getIdTipoAtividade() + "', '" + atividade.getDescricao() + "', " + atividade.getFaseIdFase() + ", " + atividade.getEstado() + ")"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_atividade"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { atividade.setIdAtividade(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Tests Proxy functionality. Indirect test.", method = "Proxy", args = { java.net.Proxy.Type.class, java.net.SocketAddress.class }) @BrokenTest("the host address isn't working anymore") public void test_openConnectionLjava_net_Proxy() throws IOException { SocketAddress addr1 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 808); SocketAddress addr2 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 1080); Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1); Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr2); Proxy proxyList[] = { proxy1, proxy2 }; for (int i = 0; i < proxyList.length; ++i) { String posted = "just a test"; URL u = new URL("http://" + Support_Configuration.ProxyServerTestHost + "/cgi-bin/test.pl"); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u.openConnection(proxyList[i]); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-length", String.valueOf(posted.length())); OutputStream out = conn.getOutputStream(); out.write(posted.getBytes()); out.close(); conn.getResponseCode(); InputStream is = conn.getInputStream(); String response = ""; byte[] b = new byte[1024]; int count = 0; while ((count = is.read(b)) > 0) { response += new String(b, 0, count); } assertTrue("Response to POST method invalid", response.equals(posted)); } URL httpUrl = new URL("http://abc.com"); URL jarUrl = new URL("jar:" + Support_Resources.getResourceURL("/JUC/lf.jar!/plus.bmp")); URL ftpUrl = new URL("ftp://" + Support_Configuration.FTPTestAddress + "/nettest.txt"); URL fileUrl = new URL("file://abc"); URL[] urlList = { httpUrl, jarUrl, ftpUrl, fileUrl }; for (int i = 0; i < urlList.length; ++i) { try { urlList[i].openConnection(null); } catch (IllegalArgumentException iae) { } } fileUrl.openConnection(Proxy.NO_PROXY); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: @SuppressWarnings("static-access") @RequestMapping(value = "/upload/upload.html", method = RequestMethod.POST) protected void save(HttpServletRequest request, HttpServletResponse response) throws ServletException { UPLOAD_DIRECTORY = uploadDiretory(); File diretorioUsuario = new File(UPLOAD_DIRECTORY); boolean diretorioCriado = false; if (!diretorioUsuario.exists()) { diretorioCriado = diretorioUsuario.mkdir(); if (!diretorioCriado) throw new RuntimeException("Não foi possível criar o diretório do usuário"); } PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(UPLOAD_DIRECTORY + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
11
Code Sample 1: public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } } Code Sample 2: public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static final String enctrypt(String password) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); throw new RuntimeException("NoSuchAlgorithmException SHA1"); } md.reset(); md.update(password.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } Code Sample 2: public static void main(String[] args) throws UnsupportedEncodingException { MessageDigest md = null; String password = "admin!@#$" + "ZKNugmkm"; try { md = MessageDigest.getInstance("SHA-512"); md.update(password.getBytes("utf8")); byte[] b = md.digest(); StringBuilder output = new StringBuilder(32); for (int i = 0; i < b.length; i++) { String temp = Integer.toHexString(b[i] & 0xff); if (temp.length() < 2) { output.append("0"); } output.append(temp); } System.out.println(output); System.out.println(output.length()); System.out.println(RandomUtils.createRandomString(8)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
00
Code Sample 1: public HashCash(String cash) throws NoSuchAlgorithmException { myToken = cash; String[] parts = cash.split(":"); myVersion = Integer.parseInt(parts[0]); if (myVersion < 0 || myVersion > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if ((myVersion == 0 && parts.length != 6) || (myVersion == 1 && parts.length != 7)) throw new IllegalArgumentException("Improperly formed HashCash"); try { int index = 1; if (myVersion == 1) myValue = Integer.parseInt(parts[index++]); else myValue = 0; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); tempCal.setTime(dateFormat.parse(parts[index++])); myResource = parts[index++]; myExtensions = deserializeExtensions(parts[index++]); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(cash.getBytes()); byte[] tempBytes = md.digest(); int tempValue = numberOfLeadingZeros(tempBytes); if (myVersion == 0) myValue = tempValue; else if (myVersion == 1) myValue = (tempValue > myValue ? myValue : tempValue); } catch (java.text.ParseException ex) { throw new IllegalArgumentException("Improperly formed HashCash", ex); } } Code Sample 2: public static byte[] request(String remoteUrl, boolean keepalive) throws Exception { Log.d(TAG, String.format("started request(remote=%s)", remoteUrl)); Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST); byte[] buffer = new byte[1024]; URL url = new URL(remoteUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setAllowUserInteraction(false); connection.setRequestProperty("Viewer-Only-Client", "1"); connection.setRequestProperty("Client-Daap-Version", "3.10"); connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); if (!keepalive) { connection.setConnectTimeout(1200000); connection.setReadTimeout(1200000); } else { connection.setReadTimeout(0); } connection.connect(); if (connection.getResponseCode() >= HttpURLConnection.HTTP_UNAUTHORIZED) throw new RequestException("HTTP Error Response Code: " + connection.getResponseCode(), connection.getResponseCode()); String encoding = connection.getContentEncoding(); InputStream inputStream = null; if (encoding != null && encoding.equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(connection.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { inputStream = new InflaterInputStream(connection.getInputStream(), new Inflater(true)); } else { inputStream = connection.getInputStream(); } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } finally { if (os != null) { os.flush(); os.close(); } if (inputStream != null) { inputStream.close(); } } return os.toByteArray(); }
00
Code Sample 1: public URLStream(URL url) throws IOException { this.url = url; this.conn = this.url.openConnection(); contentType = conn.getContentType(); name = url.toExternalForm(); size = new Long(conn.getContentLength()); sourceInfo = "url"; } Code Sample 2: private void readFromDB() throws Exception { URL url; URLConnection connect; BufferedInputStream in = null; Schema schema = new Schema(base, indexDir, false); BtreeDictParameters params = new BtreeDictParameters(schema, "TMAP"); params.readState(); tmap = new BtreeDict(params); readChildrenData(); url = getURL("DOCS.TAB"); connect = url.openConnection(); in = new BufferedInputStream(connect.getInputStream()); int k1 = in.read(); concepts = new IntegerArray(4096); StreamDecompressor sddocs = new StreamDecompressor(in); sddocs.ascDecode(k1, concepts); int k2 = in.read(); offsets = new IntegerArray(concepts.cardinality() + 1); offsets.add(0); StreamDecompressor sdoffsets = new StreamDecompressor(in); sdoffsets.ascDecode(k2, offsets); in.close(); url = getURL("DOCS"); connect = url.openConnection(); in = new BufferedInputStream(connect.getInputStream()); ByteArrayOutputStream data = new ByteArrayOutputStream(); byte[] buff = new byte[512]; int i = 0; while ((i = in.read(buff)) != -1) { data.write(buff, 0, i); } allLists = data.toByteArray(); in.close(); url = getURL("OFFSETS"); connect = url.openConnection(); in = new BufferedInputStream(connect.getInputStream()); k1 = in.read(); documents = new IntegerArray(4096); sddocs = new StreamDecompressor(in); sddocs.ascDecode(k1, documents); k2 = in.read(); offsets2 = new IntegerArray(documents.cardinality() + 1); sdoffsets = new StreamDecompressor(in); sdoffsets.ascDecode(k2, offsets2); int k3 = in.read(); titles = new IntegerArray(documents.cardinality()); StreamDecompressor sdtitles = new StreamDecompressor(in); sdtitles.decode(k3, titles); in.close(); RAFFileFactory factory = RAFFileFactory.create(); url = getURL("POSITIONS"); positionsFile = factory.get(url, false); }
11
Code Sample 1: void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); 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 boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; }
00
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 main(String[] args) throws UnsupportedEncodingException { MessageDigest md = null; String password = "admin!@#$" + "ZKNugmkm"; try { md = MessageDigest.getInstance("SHA-512"); md.update(password.getBytes("utf8")); byte[] b = md.digest(); StringBuilder output = new StringBuilder(32); for (int i = 0; i < b.length; i++) { String temp = Integer.toHexString(b[i] & 0xff); if (temp.length() < 2) { output.append("0"); } output.append(temp); } System.out.println(output); System.out.println(output.length()); System.out.println(RandomUtils.createRandomString(8)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
11
Code Sample 1: public void applyTo(File source, File target) throws IOException { boolean failed = true; FileInputStream fin = new FileInputStream(source); try { FileChannel in = fin.getChannel(); FileOutputStream fos = new FileOutputStream(target); try { FileChannel out = fos.getChannel(); long pos = 0L; for (Replacement replacement : replacements) { in.transferTo(pos, replacement.pos - pos, out); if (replacement.val != null) out.write(ByteBuffer.wrap(replacement.val)); pos = replacement.pos + replacement.len; } in.transferTo(pos, source.length() - pos, out); failed = false; } finally { fos.close(); if (failed == true) target.delete(); } } finally { fin.close(); } } Code Sample 2: private List<Document> storeDocuments(List<Document> documents) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); List<Document> newDocuments = new ArrayList<Document>(); try { session.beginTransaction(); Preference preference = new PreferenceModel(); preference = (Preference) preference.doList(preference).get(0); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); if (documents != null && !documents.isEmpty()) { for (Iterator<Document> iter = documents.iterator(); iter.hasNext(); ) { Document document = iter.next(); if (AppConstants.STATUS_ACTIVE.equals(document.getStatus())) { try { document = (Document) preAdd(document, getParams()); File fileIn = new File(preference.getScanLocation() + File.separator + document.getName()); File fileOut = new File(preference.getStoreLocation() + File.separator + document.getName()); FileInputStream in = new FileInputStream(fileIn); FileOutputStream out = new FileOutputStream(fileOut); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); document.doAdd(document); boolean isDeleted = fileIn.delete(); System.out.println("Deleted scan folder file: " + document.getName() + ":" + isDeleted); if (isDeleted) { document.setStatus(AppConstants.STATUS_PROCESSING); int uploadCount = 0; if (document.getUploadCount() != null) { uploadCount = document.getUploadCount(); } uploadCount++; document.setUploadCount(uploadCount); newDocuments.add(document); } } catch (Exception add_ex) { add_ex.printStackTrace(); } } else if (AppConstants.STATUS_PROCESSING.equals(document.getStatus())) { int uploadCount = document.getUploadCount(); if (uploadCount < 5) { uploadCount++; document.setUploadCount(uploadCount); System.out.println("increase upload count: " + document.getName() + ":" + uploadCount); newDocuments.add(document); } else { System.out.println("delete from documents list: " + document.getName()); } } else if (AppConstants.STATUS_INACTIVE.equals(document.getStatus())) { document.setFixFlag(AppConstants.FLAG_NO); newDocuments.add(document); } } } } catch (Exception ex) { ex.printStackTrace(); } return newDocuments; }
00
Code Sample 1: public void testSnapPullWithMasterUrl() throws Exception { copyFile(new File(CONF_DIR + "solrconfig-slave1.xml"), new File(slave.getConfDir(), "solrconfig.xml")); slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); for (int i = 0; i < 500; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = query("*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(500, masterQueryResult.getNumFound()); String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=fetchindex&masterUrl="; masterUrl += "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication"; URL url = new URL(masterUrl); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { } Thread.sleep(3000); NamedList slaveQueryRsp = query("*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(500, slaveQueryResult.getNumFound()); String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); } Code Sample 2: public void mousePressed(MouseEvent e) { bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(bannerURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); HttpHost host = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); String targetURL = host.toURI() + request.getURI(); DesktopUtil.browseAndWarn(targetURL, bannerLbl); EntityUtils.consume(entity); } catch (Exception ex) { NotifyUtil.error("Banner Error", "Could not open the default web browser.", ex, false); } finally { method.abort(); } bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); }
11
Code Sample 1: public FileInputStream execute() { FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); String pdfPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf"); try { FileOutputStream outputStream = new FileOutputStream(pdfPath + "/driveTogether.pdf"); PdfWriter writer = PdfWriter.getInstance(doc, outputStream); doc.open(); String pfad = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf/template.pdf"); logger.info("Loading PDF-Template: " + pfad); PdfReader reader = new PdfReader(pfad); PdfImportedPage page = writer.getImportedPage(reader, 1); PdfContentByte cb = writer.getDirectContent(); cb.addTemplate(page, 0, 0); doHeader(); doParagraph(trip, forUser); doc.close(); fis = new FileInputStream(pdfPath + "/driveTogether.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fis; } 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."); }