label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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:
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); if (login) { postURL = "http://upload.badongo.com/mpu_upload.php"; } HttpPost httppost = new HttpPost(postURL); file = new File("g:/S2SClient.7z"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); if (login) { mpEntity.addPart("PHPSESSID", new StringBody(dataid)); } mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into badongo.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("Upload response : " + uploadresponse); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("res " + uploadresponse); httpclient.getConnectionManager().shutdown(); }
|
00
|
Code Sample 1:
public static String obterConteudoSite(String u) { URL url; try { url = new URL(u); URLConnection conn = null; if (proxy != null) conn = url.openConnection(proxy.getProxy()); else conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); String line; StringBuilder resultado = new StringBuilder(); while ((line = rd.readLine()) != null) { resultado.append(line); resultado.append("\n"); } rd.close(); return resultado.toString(); } catch (MalformedURLException e) { throw new AlfredException("Não foi possível obter contato com o site " + u, e); } catch (IOException e) { throw new AlfredException("Não foi possível obter contato com o site " + u, e); } }
Code Sample 2:
public void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
|
11
|
Code Sample 1:
public static void copy(final File src, final File dst) throws IOException, IllegalArgumentException { long fileSize = src.length(); final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } src.delete(); } }
Code Sample 2:
public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } }
|
00
|
Code Sample 1:
public EVECalcControllerImpl(EVECalcView gui) { this.view = gui; properties = new Properties(); try { InputStream resStream; resStream = getClass().getResourceAsStream(REGION_PROPERTIES); if (resStream == null) { System.out.println("Loading for needed Properties files failed."); URL url = new URL(REGIONS_URL); try { resStream = url.openStream(); properties.load(resStream); } catch (Exception e) { e.printStackTrace(); } } else { properties.load(resStream); } } catch (IOException e) { } }
Code Sample 2:
public String get(String url) { String buf = null; StringBuilder resultBuffer = new StringBuilder(512); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(url)>> " + url); try { URL theURL = new URL(url); URLConnection urlConn = theURL.openConnection(); urlConn.setDoOutput(true); urlConn.setReadTimeout(timeOut); BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); do { buf = urlReader.readLine(); if (buf != null) { resultBuffer.append(buf); resultBuffer.append("\n"); } } while (buf != null); urlReader.close(); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(output)>> " + resultBuffer.toString()); int xmlNdx = resultBuffer.lastIndexOf("?>"); if (xmlNdx == -1) result = resultBuffer.toString(); else result = resultBuffer.substring(xmlNdx + 2); } catch (Exception e) { result = debug.logger("gov.llnl.tox.util.href", "error: get >> ", e); } return (result); }
|
00
|
Code Sample 1:
public static <T extends Comparable<T>> void BubbleSortComparable2(T[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j].compareTo(num[j + 1]) > 0) { T temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
Code Sample 2:
public static String doPostEntity(String URL, List<NameValuePair> params) { try { OauthUtil util = new OauthUtil(); URI uri = new URI(URL); HttpClient httpclient = util.getNewHttpClient(); HttpPost postMethod = new HttpPost(uri); postMethod.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = httpclient.execute(postMethod); if (httpResponse.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(httpResponse.getEntity()); Log.i("DEBUG", "result: " + strResult); String token; try { JSONObject obj = new JSONObject(strResult); token = obj.getString("access_token"); } catch (Exception e) { token = strResult.substring(strResult.indexOf("access_token=") + 13); } return token; } } catch (Exception e) { Log.i("DEBUG", e.toString()); } return null; }
|
11
|
Code Sample 1:
@Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } }
Code Sample 2:
private void doTask() { try { log("\n\n\n\n\n\n\n\n\n"); log(" ================================================="); log(" = Starting PSCafePOS ="); log(" ================================================="); log(" = An open source point of sale system ="); log(" = for educational organizations. ="); log(" ================================================="); log(" = General Information ="); log(" = http://pscafe.sourceforge.net ="); log(" = Free Product Support ="); log(" = http://www.sourceforge.net/projects/pscafe ="); log(" ================================================="); log(" = License Overview ="); log(" ================================================="); log(" = PSCafePOS is a POS System for Schools ="); log(" = Copyright (C) 2007 Charles Syperski ="); log(" = ="); log(" = This program is free software; you can ="); log(" = redistribute it and/or modify it under the ="); log(" = terms of the GNU General Public License as ="); log(" = published by the Free Software Foundation; ="); log(" = either version 2 of the License, or any later ="); log(" = version. ="); log(" = ="); log(" = This program is distributed in the hope that ="); log(" = it will be useful, but WITHOUT ANY WARRANTY; ="); log(" = without even the implied warranty of ="); log(" = MERCHANTABILITY or FITNESS FOR A PARTICULAR ="); log(" = PURPOSE. ="); log(" = ="); log(" = See the GNU General Public License for more ="); log(" = details. ="); log(" = ="); log(" = You should have received a copy of the GNU ="); log(" = General Public License along with this ="); log(" = program; if not, write to the ="); log(" = ="); log(" = Free Software Foundation, Inc. ="); log(" = 59 Temple Place, Suite 330 ="); log(" = Boston, MA 02111-1307 USA ="); log(" ================================================="); log(" = If you have any questions of comments please ="); log(" = let us know at http://pscafe.sourceforge.net ="); log(" ================================================="); pause(); File settings; if (blAltSettings) { System.out.println("\n + Alternative path specified at run time:"); System.out.println(" Path: " + strAltPath); settings = new File(strAltPath); } else { settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Checking for existance of settings..."); boolean blGo = false; if (settings.exists() && settings.canRead()) { log("[OK]"); blGo = true; if (forceConfig) { System.out.print("\n + Running Config Wizard (at user request)..."); Process pp = Runtime.getRuntime().exec("java -cp . PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = pp.getErrorStream(); InputStream stdin = pp.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); pp.waitFor(); } } else { log("[FAILED]"); settings = new File("etc" + File.separatorChar + "settings.dbp.firstrun"); System.out.print("\n + Checking if this is the first run... "); if (settings.exists() && settings.canRead()) { log("[FOUND]"); File toFile = new File("etc" + File.separatorChar + "settings.dbp"); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(settings); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } if (toFile.exists() && toFile.canRead()) { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Running Settings Wizard... "); try { Process p = Runtime.getRuntime().exec("java PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = p.getErrorStream(); InputStream stdin = p.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); p.waitFor(); log("[OK]"); if (p.exitValue() == 0) blGo = true; } catch (InterruptedException i) { System.err.println(i.getMessage()); } } catch (Exception ex) { System.err.println(ex.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } else { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); DBSettingsWriter writ = new DBSettingsWriter(); writ.writeFile(new DBSettings(), settings); blGo = true; } } if (blGo) { String cp = "."; try { File classpath = new File("lib"); File[] subFiles = classpath.listFiles(); for (int i = 0; i < subFiles.length; i++) { if (subFiles[i].isFile()) { cp += File.pathSeparatorChar + "lib" + File.separatorChar + subFiles[i].getName() + ""; } } } catch (Exception e) { System.err.println(e.getMessage()); } try { boolean blExecutePOS = false; System.out.print("\n + Checking runtime settings... "); DBSettings info = null; if (settings == null) settings = new File("etc" + File.separatorChar + "settings.dbp"); if (settings.exists() && settings.canRead()) { DBSettingsWriter writ = new DBSettingsWriter(); info = (DBSettings) writ.loadSettingsDB(settings); if (info != null) { blExecutePOS = true; } } if (blExecutePOS) { log("[OK]"); String strSSL = ""; String strSSLDebug = ""; if (info != null) { debug = info.get(DBSettings.MAIN_DEBUG).compareTo("1") == 0; if (debug) log(" * Debug Mode is ON"); else log(" * Debug Mode is OFF"); if (info.get(DBSettings.POS_SSLENABLED).compareTo("1") == 0) { strSSL = "-Djavax.net.ssl.keyStore=" + info.get(DBSettings.POS_SSLKEYSTORE) + " -Djavax.net.ssl.keyStorePassword=pscafe -Djavax.net.ssl.trustStore=" + info.get(DBSettings.POS_SSLTRUSTSTORE) + " -Djavax.net.ssl.trustStorePassword=pscafe"; log(" * Using SSL"); debug(" " + strSSL); if (info.get(DBSettings.POS_SSLDEBUG).compareTo("1") == 0) { strSSLDebug = "-Djavax.net.debug=all"; log(" * SSL Debugging enabled"); debug(" " + strSSLDebug); } } } String strPOSRun = "java -cp " + cp + " " + strSSL + " " + strSSLDebug + " POSDriver " + settings.getPath(); debug(strPOSRun); System.out.print("\n + Running PSCafePOS... "); Process pr = Runtime.getRuntime().exec(strPOSRun); System.out.print("[OK]\n\n"); InputStream stderr = pr.getErrorStream(); InputStream stdin = pr.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); InputStreamReader isre = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); BufferedReader bre = new BufferedReader(isre); String line = null; String lineError = null; log(" ================================================="); log(" = Output from PSCafePOS System ="); log(" ================================================="); while ((line = br.readLine()) != null || (lineError = bre.readLine()) != null) { if (line != null) System.out.println(" [PSCafePOS]" + line); if (lineError != null) System.out.println(" [ERR]" + lineError); } pr.waitFor(); log(" ================================================="); log(" = End output from PSCafePOS System ="); log(" = PSCafePOS has exited ="); log(" ================================================="); } else { log("[Failed]"); } } catch (Exception i) { log(i.getMessage()); i.printStackTrace(); } } } catch (Exception e) { log(e.getMessage()); } }
|
00
|
Code Sample 1:
public final void provisionGSLAM() { try { UUID[] slaUUID = new UUID[] { new UUID("AG-1") }; SLA[] slas = sslamContext.getSLARegistry().getIQuery().getSLA(slaUUID); for (SLA s : slas) { Party[] parties = s.getParties(); System.out.println("SLA Info :::" + s.getUuid().toString()); for (Party p : parties) { System.out.println("Printing gslam_epr value for Party" + p.getId() + "--" + p.getAgreementRole()); System.out.println(parties[0].getPropertyValue(new STND("gslam_epr"))); } } sslamContext.getSLARegistry().getIRegister().register(slas[0], slaUUID, SLAState.OBSERVED); String xmlFile2Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "provision.xml"; String soapAction = ""; URL url; url = new URL(syntaxConverterNegotiationWSURL); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn.setRequestProperty("SOAPAction", soapAction); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder db; db = factory.newDocumentBuilder(); org.xml.sax.InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(new java.io.StringReader(response.toString())); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: GSLAM\n" + "Interface Name: negotiate/coordinage\n" + "Operation Name: Provision\n" + "Input:Type " + "void" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (RegistrationFailureException e) { e.printStackTrace(); } catch (SLAManagerContextException e) { e.printStackTrace(); } catch (InvalidUUIDException e) { e.printStackTrace(); } }
Code Sample 2:
public void test(TestHarness harness) { harness.checkPoint("TestOfMD4"); try { Security.addProvider(new JarsyncProvider()); algorithm = MessageDigest.getInstance("BrokenMD4", "JARSYNC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); throw new Error(x); } try { for (int i = 0; i < 64; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "755cd64425f260e356f5303ee82a2d5f"; harness.check(exp.equals(Util.toHexString(md)), "testSixtyFourA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { harness.verbose("NOTE: This test may take a while."); for (int i = 0; i < 536870913; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "b6cea9f528a85963f7529a9e3a2153db"; harness.check(exp.equals(Util.toHexString(md)), "test536870913A"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { byte[] md = algorithm.digest("a".getBytes()); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testA"); } try { byte[] md = algorithm.digest("abc".getBytes()); String exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testABC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testABC"); } try { byte[] md = algorithm.digest("message digest".getBytes()); String exp = "d9130a8164549fe818874806e1c7014b"; harness.check(exp.equals(Util.toHexString(md)), "testMessageDigest"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testMessageDigest"); } try { byte[] md = algorithm.digest("abcdefghijklmnopqrstuvwxyz".getBytes()); String exp = "d79e1c308aa5bbcdeea8ed63df412da9"; harness.check(exp.equals(Util.toHexString(md)), "testAlphabet"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAlphabet"); } try { byte[] md = algorithm.digest("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".getBytes()); String exp = "043f8582f241db351ce627e153e7f0e4"; harness.check(exp.equals(Util.toHexString(md)), "testAsciiSubset"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAsciiSubset"); } try { byte[] md = algorithm.digest("12345678901234567890123456789012345678901234567890123456789012345678901234567890".getBytes()); String exp = "e33b4ddc9c38f2199c3e7b164fcc0536"; harness.check(exp.equals(Util.toHexString(md)), "testEightyNumerics"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testEightyNumerics"); } try { algorithm.update("a".getBytes(), 0, 1); clone = (MessageDigest) algorithm.clone(); byte[] md = algorithm.digest(); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #1"); clone.update("bc".getBytes(), 0, 2); md = clone.digest(); exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #2"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testCloning"); } }
|
00
|
Code Sample 1:
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); TextView tv = new TextView(this); try { URL url = new URL(""); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); ExampleHandler myExampleHandler = new ExampleHandler(); xr.setContentHandler(myExampleHandler); xr.parse(new InputSource(url.openStream())); ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData(); tv.setText(parsedExampleDataSet.toString()); } catch (Exception e) { tv.setText("Error: " + e.getMessage()); Log.e(MY_DEBUG_TAG, "WeatherQueryError", e); } this.setContentView(tv); }
Code Sample 2:
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; }
|
00
|
Code Sample 1:
protected Class findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (this.extensionJars != null) { for (int i = 0; i < this.extensionJars.length; i++) { JarFile extensionJar = this.extensionJars[i]; JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } }
Code Sample 2:
@SuppressWarnings("finally") private void compress(File src) throws IOException { if (this.switches.contains(Switch.test)) return; checkSourceFile(src); if (src.getPath().endsWith(".bz2")) { this.log.println("WARNING: skipping file because it already has .bz2 suffix:").println(src); return; } final File dst = new File(src.getPath() + ".bz2").getAbsoluteFile(); if (!checkDestFile(dst)) return; FileChannel inChannel = null; FileChannel outChannel = null; FileOutputStream fileOut = null; BZip2OutputStream bzOut = null; FileLock inLock = null; FileLock outLock = null; try { inChannel = new FileInputStream(src).getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); fileOut = new FileOutputStream(dst); outChannel = fileOut.getChannel(); bzOut = new BZip2OutputStream( new BufferedXOutputStream(fileOut, 8192), Math.min( (this.blockSize == -1) ? BZip2OutputStream.MAX_BLOCK_SIZE : this.blockSize, BZip2OutputStream.chooseBlockSize(inSize) ) ); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); final boolean showProgress = this.switches.contains(Switch.showProgress); long pos = 0; int progress = 0; if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } while (true) { final long maxStep = showProgress ? Math.max(8192, (inSize - pos) / MAX_PROGRESS) : (inSize - pos); if (maxStep <= 0) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } else { final long step = inChannel.transferTo(pos, maxStep, bzOut); if ((step == 0) && (inChannel.size() != inSize)) throw error("file " + src + " has been modified concurrently by another process"); pos += step; if (showProgress) { final double p = (double) pos / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } inLock.release(); inChannel.close(); bzOut.closeInstance(); final long outSize = outChannel.position(); outChannel.truncate(outSize); outLock.release(); fileOut.close(); if (this.verbose) { final double ratio = (inSize == 0) ? (outSize * 100) : ((double) outSize / (double) inSize); this.log.print("raw size: ").print(inSize) .print("; compressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } } catch (final IOException ex) { IO.tryClose(inChannel); IO.tryClose(bzOut); IO.tryClose(fileOut); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } }
|
00
|
Code Sample 1:
public static String sendGetData(URL url, Hashtable<String, String> data) throws IOException { StringBuilder outStringBuilder = new StringBuilder(); if (data != null) { for (Entry<String, String> entry : data.entrySet()) { outStringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")); outStringBuilder.append("="); outStringBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8")); outStringBuilder.append("&"); } } URL innerURL = new URL(url.toString() + "?" + outStringBuilder.toString()); System.out.println("URL: " + innerURL); URLConnection urlConnection = innerURL.openConnection(); urlConnection.connect(); StringBuilder inStringBuilder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); Scanner inputScanner = new Scanner(urlConnection.getInputStream()); while (inputScanner.hasNext()) { inStringBuilder.append(inputScanner.next() + " "); } inputScanner.close(); reader.close(); return inStringBuilder.toString(); }
Code Sample 2:
public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }
|
11
|
Code Sample 1:
public static void testclass(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.emptyClass(ClassWriter.ACC_PUBLIC, "TestClass", "java/lang/Object"); MethodInfo newMethod = writer.addMethod(ClassWriter.ACC_PUBLIC | ClassWriter.ACC_STATIC, "main", "([Ljava/lang/String;)V"); CodeAttribute attribute = newMethod.getCodeAttribute(); int constantIndex = writer.getStringConstantIndex("It's alive! It's alive!!"); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int methodRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); ArrayList instructions = new ArrayList(); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); operands = new byte[1]; operands[0] = (byte) constantIndex; instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("ldc"), 0, operands, false)); operands = new byte[2]; NetByte.intToPair(methodRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("return"), 0, null, false)); attribute.insertInstructions(0, 0, instructions); attribute.setMaxLocals(1); attribute.codeCheck(); System.out.println("constantIndex=" + constantIndex + " fieldRef=" + fieldRefIndex + " methodRef=" + methodRefIndex); writer.writeClass(new FileOutputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); writer.readClass(new FileInputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); }
Code Sample 2:
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
|
11
|
Code Sample 1:
public void testCommitRollback() throws Exception { Statement stmt = con.createStatement(); assertNotNull(stmt); assertTrue(con.getAutoCommit()); stmt.execute("CREATE TABLE #TESTCOMMIT (id int primary key)"); con.setAutoCommit(false); assertFalse(con.getAutoCommit()); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (1)")); con.commit(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (2)")); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (3)")); con.rollback(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (4)")); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM #TESTCOMMIT"); rs.next(); assertEquals("commit", 2, rs.getInt(1)); stmt.close(); }
Code Sample 2:
public void updatePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public TempFileBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".bin"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
|
00
|
Code Sample 1:
private void process(int optind, String args[]) throws IOException, XMLStreamException { final int srlimit = 500; final QName att_title = new QName("title"); final QName att_sroffset = new QName("sroffset"); String sroffset = null; String srnamespace = null; if (!this.srnamespaces.isEmpty()) { StringBuilder sb = new StringBuilder(); for (Integer i : this.srnamespaces) { if (sb.length() > 0) sb.append("|"); sb.append(String.valueOf(i)); } srnamespace = sb.toString(); } StringBuilder terms = new StringBuilder(); while (optind < args.length) { if (terms.length() > 0) terms.append(" "); terms.append(args[optind++]); } while (true) { String url = this.base_api + "?action=query" + "&list=search" + "&format=xml" + "&srsearch=" + URLEncoder.encode(terms.toString(), "UTF-8") + (srnamespace != null ? "&srnamespace=" + srnamespace : "") + (sroffset == null ? "" : "&sroffset=" + sroffset) + "&srlimit=" + srlimit + "&srwhat=text&srprop=timestamp"; sroffset = null; LOG.info(url); XMLEventReader reader = this.xmlInputFactory.createXMLEventReader(openStream(url)); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement e = event.asStartElement(); String name = e.getName().getLocalPart(); Attribute att = null; if (name.equals("p") && (att = e.getAttributeByName(att_title)) != null) { System.out.println(att.getValue()); } else if (name.equals("search") && (att = e.getAttributeByName(att_sroffset)) != null) { sroffset = att.getValue(); } } } reader.close(); if (sroffset == null) break; } }
Code Sample 2:
public static void main(final String[] args) throws RecognitionException, TokenStreamException, IOException, IllegalOptionValueException, UnknownOptionException { try { CmdLineParser cmdLineParser = new CmdLineParser(); Option formatOption = cmdLineParser.addStringOption('f', "format"); Option encodingOption = cmdLineParser.addStringOption('c', "charset"); cmdLineParser.parse(args); String format = (String) cmdLineParser.getOptionValue(formatOption); String encoding = (String) cmdLineParser.getOptionValue(encodingOption); if (encoding == null || encoding.trim().equals("")) { encoding = "utf-8"; System.out.println("Defaulting to output charset utf-8 as argument -c is missing or not valid."); } String[] remainingArgs = cmdLineParser.getRemainingArgs(); if (remainingArgs.length != 2) { printUsage("Input and output file are not specified correctly. "); } File inputFile = new File(remainingArgs[0]); if (!inputFile.exists()) { printUsage("Input file " + remainingArgs[0] + " does not exist. "); } File outputFile = new File(remainingArgs[1]); if (!outputFile.exists()) { outputFile.createNewFile(); } if (format == null || format.trim().equals("")) { format = (String) FileUtil.cutExtension(outputFile.getName()).getValue(); } if ("tex".equals(format)) { Reader reader = new LatexEncoderReader(new FileReader(inputFile)); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outputFile), encoding); char[] buffer = new char[1024]; int read; do { read = reader.read(buffer); if (read > 0) { out.write(buffer, 0, read); } } while (read != -1); out.flush(); out.close(); } else { printUsage("Format not specified via argument -f. Also guessing for the extension of output file " + outputFile.getName() + " failed"); } } catch (Exception ex) { ex.printStackTrace(); printUsage(ex.getMessage()); } }
|
00
|
Code Sample 1:
public void copyFile(File from, File to) { try { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); int readCount; byte[] bytes = new byte[1024]; while ((readCount = in.read(bytes)) != -1) { out.write(bytes, 0, readCount); } out.flush(); in.close(); out.close(); } catch (Exception ex) { throw new BuildException(ex.getMessage(), ex); } }
Code Sample 2:
@Override public String post(final FetchInfos fetchInfos, final String data) throws HttpException { URL url = null; try { url = new URL(fetchInfos.getUri()); } catch (MalformedURLException exception) { throw new HttpException("uri is malformed '" + fetchInfos.getUri() + "'", exception); } HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } InputStream input = null; try { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); final DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); input = connection.getInputStream(); if ("gzip".equals(connection.getHeaderField("content-encoding"))) { input = new GZIPInputStream(input); } if (HttpServiceImpl.LOGGER.isDebugEnabled()) { this.logConnection(connection); input = new LoggingInputStream(input); } } catch (SocketTimeoutException exception) { fetchInfos.setResult(FETCHING_RESULT.TIME_OUT); throw new HttpException("get '" + fetchInfos.getUri() + "' timeout", exception); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } fetchInfos.setResult(FETCHING_RESULT.OK); String response = null; try { response = this.toString(input); } catch (IOException exception) { throw new HttpException("converting inputstream to string failed", exception); } return response; }
|
11
|
Code Sample 1:
public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } }
Code Sample 2:
public static void testclass(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.emptyClass(ClassWriter.ACC_PUBLIC, "TestClass", "java/lang/Object"); MethodInfo newMethod = writer.addMethod(ClassWriter.ACC_PUBLIC | ClassWriter.ACC_STATIC, "main", "([Ljava/lang/String;)V"); CodeAttribute attribute = newMethod.getCodeAttribute(); int constantIndex = writer.getStringConstantIndex("It's alive! It's alive!!"); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int methodRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); ArrayList instructions = new ArrayList(); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); operands = new byte[1]; operands[0] = (byte) constantIndex; instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("ldc"), 0, operands, false)); operands = new byte[2]; NetByte.intToPair(methodRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("return"), 0, null, false)); attribute.insertInstructions(0, 0, instructions); attribute.setMaxLocals(1); attribute.codeCheck(); System.out.println("constantIndex=" + constantIndex + " fieldRef=" + fieldRefIndex + " methodRef=" + methodRefIndex); writer.writeClass(new FileOutputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); writer.readClass(new FileInputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); }
|
11
|
Code Sample 1:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } }
Code Sample 2:
public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
|
00
|
Code Sample 1:
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Code Sample 2:
public ClientDTO changePassword(String pMail, String pMdp) { Client vClientBean = null; ClientDTO vClientDTO = null; vClientBean = mClientDao.getClient(pMail); if (vClientBean != null) { MessageDigest vMd5Instance; try { vMd5Instance = MessageDigest.getInstance("MD5"); vMd5Instance.reset(); vMd5Instance.update(pMdp.getBytes()); byte[] vDigest = vMd5Instance.digest(); BigInteger vBigInt = new BigInteger(1, vDigest); String vHashPassword = vBigInt.toString(16); vClientBean.setMdp(vHashPassword); vClientDTO = BeanToDTO.getInstance().createClientDTO(vClientBean); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return vClientDTO; }
|
11
|
Code Sample 1:
public Long addRole(AuthSession authSession, RoleBean roleBean) { PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_AUTH_ACCESS_GROUP"); seq.setTableName("WM_AUTH_ACCESS_GROUP"); seq.setColumnName("ID_ACCESS_GROUP"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_AUTH_ACCESS_GROUP " + "( ID_ACCESS_GROUP, NAME_ACCESS_GROUP ) values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); RsetTools.setLong(ps, 1, sequenceValue); ps.setString(2, roleBean.getName()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new role"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
Code Sample 2:
int doOne(int bid, int tid, int aid, int delta) { int aBalance = 0; if (Conn == null) { incrementFailedTransactionCount(); return 0; } try { if (prepared_stmt) { pstmt1.setInt(1, delta); pstmt1.setInt(2, aid); pstmt1.executeUpdate(); pstmt1.clearWarnings(); pstmt2.setInt(1, aid); ResultSet RS = pstmt2.executeQuery(); pstmt2.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } pstmt3.setInt(1, delta); pstmt3.setInt(2, tid); pstmt3.executeUpdate(); pstmt3.clearWarnings(); pstmt4.setInt(1, delta); pstmt4.setInt(2, bid); pstmt4.executeUpdate(); pstmt4.clearWarnings(); pstmt5.setInt(1, tid); pstmt5.setInt(2, bid); pstmt5.setInt(3, aid); pstmt5.setInt(4, delta); pstmt5.executeUpdate(); pstmt5.clearWarnings(); } else { Statement Stmt = Conn.createStatement(); String Query = "UPDATE accounts "; Query += "SET Abalance = Abalance + " + delta + " "; Query += "WHERE Aid = " + aid; int res = Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "SELECT Abalance "; Query += "FROM accounts "; Query += "WHERE Aid = " + aid; ResultSet RS = Stmt.executeQuery(Query); Stmt.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } Query = "UPDATE tellers "; Query += "SET Tbalance = Tbalance + " + delta + " "; Query += "WHERE Tid = " + tid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "UPDATE branches "; Query += "SET Bbalance = Bbalance + " + delta + " "; Query += "WHERE Bid = " + bid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "INSERT INTO history(Tid, Bid, Aid, delta) "; Query += "VALUES ("; Query += tid + ","; Query += bid + ","; Query += aid + ","; Query += delta + ")"; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Stmt.close(); } if (transactions) { Conn.commit(); } return aBalance; } catch (Exception E) { if (verbose) { System.out.println("Transaction failed: " + E.getMessage()); E.printStackTrace(); } incrementFailedTransactionCount(); if (transactions) { try { Conn.rollback(); } catch (SQLException E1) { } } } return 0; }
|
11
|
Code Sample 1:
protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); }
Code Sample 2:
public static List<String> unTar(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); TarArchiveInputStream in = new TarArchiveInputStream(inputStream); TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextTarEntry(); } in.close(); return result; }
|
00
|
Code Sample 1:
private void translate(String sender, String message) { StringTokenizer st = new StringTokenizer(message, " "); message = message.replaceFirst(st.nextToken(), ""); String typeCode = st.nextToken(); message = message.replaceFirst(typeCode, ""); try { String data = URLEncoder.encode(message, "UTF-8"); URL url = new URL("http://babelfish.altavista.com/babelfish/tr?doit=done&urltext=" + data + "&lp=" + typeCode); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.contains("input type=hidden name=\"q\"")) { String[] tokens = line.split("\""); sendMessage(sender, tokens[3]); } } wr.close(); rd.close(); } catch (Exception e) { } }
Code Sample 2:
public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
@Override protected String doInBackground(MarketData... market) { publishProgress(-1); InputStream input = null; OutputStream output = null; long lenghtOfFile = 0; int lengthRead = 0; try { HttpGet newReq = new HttpGet(market[0].apkURL); HttpResponse response = HttpManager.execute(newReq); Log.i(Main.TAG, "req:" + response.getStatusLine().getStatusCode()); while (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY) { Log.i(Main.TAG, "redirect to:" + response.getFirstHeader("Location").getValue()); newReq = new HttpGet(response.getFirstHeader("Location").getValue()); response = HttpManager.execute(newReq); Log.i(Main.TAG, "req:" + response.getStatusLine().getStatusCode()); } lenghtOfFile = response.getEntity().getContentLength(); input = response.getEntity().getContent(); output = new FileOutputStream(market[0].getFile()); lengthRead = copy(input, output, lenghtOfFile); } catch (MalformedURLException e) { Log.w(Main.TAG, "error downloading " + market[0].apkURL, e); } catch (IOException e) { Log.w(Main.TAG, "error downloading " + market[0].apkURL, e); } finally { Log.v(Main.TAG, "failed to download " + market[0].apkURL + " " + lengthRead + "/" + lenghtOfFile); if (lenghtOfFile != 0 && lengthRead != lenghtOfFile) { Log.w(Main.TAG, "failed to download " + market[0].apkURL + " " + lengthRead + "/" + lenghtOfFile); try { if (input != null) input.close(); if (output != null) output.close(); market[0].getFile().delete(); } catch (IOException e) { e.printStackTrace(); } } } Log.v(Main.TAG, "copied " + market[0].apkURL + " to " + market[0].getFile()); return null; }
Code Sample 2:
public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
|
00
|
Code Sample 1:
public static XMLShowInfo NzbSearch(TVRageShowInfo tvrage, XMLShowInfo xmldata, int latestOrNext) { String newzbin_query = "", csvData = "", hellaQueueDir = "", newzbinUsr = "", newzbinPass = ""; String[] tmp; DateFormat tvRageDateFormat = new SimpleDateFormat("MMM/dd/yyyy"); DateFormat tvRageDateFormatFix = new SimpleDateFormat("yyyy-MM-dd"); newzbin_query = "?q=" + xmldata.showName + "+"; if (latestOrNext == 0) { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.latestSeasonNum + "x" + tvrage.latestEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.latestSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.latestAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.latestTitle; } else { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.nextSeasonNum + "x" + tvrage.nextEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.nextSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.nextAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.nextTitle; } newzbin_query += "&searchaction=Search"; newzbin_query += "&fpn=p"; newzbin_query += "&category=8category=11"; newzbin_query += "&area=-1"; newzbin_query += "&u_nfo_posts_only=0"; newzbin_query += "&u_url_posts_only=0"; newzbin_query += "&u_comment_posts_only=0"; newzbin_query += "&u_v3_retention=1209600"; newzbin_query += "&ps_rb_language=" + xmldata.language; newzbin_query += "&sort=ps_edit_date"; newzbin_query += "&order=desc"; newzbin_query += "&areadone=-1"; newzbin_query += "&feed=csv"; newzbin_query += "&ps_rb_video_format=" + xmldata.format; newzbin_query = newzbin_query.replaceAll(" ", "%20"); System.out.println("http://v3.newzbin.com/search/" + newzbin_query); try { URL url = new URL("http://v3.newzbin.com/search/" + newzbin_query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); csvData = in.readLine(); if (csvData != null) { JavaNZB.searchCount++; if (searchCount == 6) { searchCount = 0; System.out.println("Sleeping for 60 seconds"); try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } tmp = csvData.split(","); tmp[2] = tmp[2].substring(1, tmp[2].length() - 1); tmp[3] = tmp[3].substring(1, tmp[3].length() - 1); Pattern p = Pattern.compile("[\\\\</:>?\\[|\\]\"]"); Matcher matcher = p.matcher(tmp[3]); tmp[3] = matcher.replaceAll(" "); tmp[3] = tmp[3].replaceAll("&", "and"); URLConnection urlConn; DataOutputStream printout; url = new URL("http://v3.newzbin.com/api/dnzb/"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "username=" + JavaNZB.newzbinUsr + "&password=" + JavaNZB.newzbinPass + "&reportid=" + tmp[2]; printout.writeBytes(content); printout.flush(); printout.close(); BufferedReader nzbInput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String format = ""; if (xmldata.format.equals("17")) format = " Xvid"; if (xmldata.format.equals("131072")) format = " x264"; if (xmldata.format.equals("2")) format = " DVD"; if (xmldata.format.equals("4")) format = " SVCD"; if (xmldata.format.equals("8")) format = " VCD"; if (xmldata.format.equals("32")) format = " HDts"; if (xmldata.format.equals("64")) format = " WMV"; if (xmldata.format.equals("128")) format = " Other"; if (xmldata.format.equals("256")) format = " ratDVD"; if (xmldata.format.equals("512")) format = " iPod"; if (xmldata.format.equals("1024")) format = " PSP"; File f = new File(JavaNZB.hellaQueueDir, tmp[3] + format + ".nzb"); BufferedWriter out = new BufferedWriter(new FileWriter(f)); String str; System.out.println("--Downloading " + tmp[3] + format + ".nzb" + " to queue directory--"); while (null != ((str = nzbInput.readLine()))) out.write(str); nzbInput.close(); out.close(); if (latestOrNext == 0) { xmldata.episode = tvrage.latestEpisodeNum; xmldata.season = tvrage.latestSeasonNum; } else { xmldata.episode = tvrage.nextEpisodeNum; xmldata.season = tvrage.nextSeasonNum; } } else System.out.println("No new episode posted"); System.out.println(); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println("IO Exception from NzbSearch"); } return xmldata; }
Code Sample 2:
private void populateJarsFromManifest(Set<String> jars, ClassLoader loader) { BufferedReader reader = null; try { Enumeration<URL> e = loader.getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { URL url = e.nextElement(); if (url.getPath().contains(SURE_FIRE_BOOTER_JAR)) { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; StringBuffer content = new StringBuffer(); while ((line = reader.readLine()) != null) { content.append(line.trim()); } String cont = content.toString().replaceAll("Manifest-Version: 1.0Class-Path: ", "").replaceAll("Main-Class: org.apache.maven.surefire.booter.SurefireBooter", ""); for (String file : cont.split(" ")) { if (file.contains("file")) { jars.add(file.replaceAll("file:", "")); } } break; } } } catch (IOException e) { log.error("", e); } finally { try { if (reader != null) { reader.close(); } } catch (Exception e) { log.error("", e); } } }
|
11
|
Code Sample 1:
private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; }
Code Sample 2:
private byte[] getMergedContent(List names, ServletContext servletContext) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (Iterator iterator = names.iterator(); iterator.hasNext(); ) { String path = (String) iterator.next(); if (!path.startsWith("/")) path = "/" + path; URL url = servletContext.getResource(path); if (url == null) url = getClass().getResource(path); if (url == null) throw new IOException("The resources '" + path + "' could not be found neither in the webapp folder nor in a jar"); log.debug("Merging content of group : " + getName()); InputStream inputStream = url.openStream(); InputStreamReader r = new InputStreamReader(inputStream); IOUtils.copy(r, baos, "ASCII"); baos.write((byte) '\n'); inputStream.close(); } baos.close(); return baos.toByteArray(); }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File targetFile) throws IOException { if (sourceFile == null || targetFile == null) { throw new NullPointerException("Source file and target file must not be null"); } File directory = targetFile.getParentFile(); if (!directory.exists() && !directory.mkdirs()) { throw new IOException("Could not create directory '" + directory + "'"); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); try { byte[] buffer = new byte[32768]; for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) { outputStream.write(buffer, 0, readBytes); } } catch (IOException ex) { targetFile.delete(); throw ex; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } }
Code Sample 2:
public void deployDir(File srcDir, String destDir) { File[] dirFiles = srcDir.listFiles(); for (int k = 0; dirFiles != null && k < dirFiles.length; k++) { if (!dirFiles[k].getName().startsWith(".")) { if (dirFiles[k].isFile()) { File deployFile = new File(destDir + File.separator + dirFiles[k].getName()); if (dirFiles[k].lastModified() != deployFile.lastModified() || dirFiles[k].length() != deployFile.length()) { IOUtils.copy(dirFiles[k], deployFile); } } else if (dirFiles[k].isDirectory()) { String newDestDir = destDir + File.separator + dirFiles[k].getName(); deployDir(dirFiles[k], newDestDir); } } } }
|
00
|
Code Sample 1:
private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } }
Code Sample 2:
public static void uploadFile(String localPath, String hostname, String username, String password, String remotePath) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(hostname); int reply = ftpClient.getReplyCode(); boolean success = false; if (FTPReply.isPositiveCompletion(reply)) { success = ftpClient.login(username, password); if (!success) { Output.error("Failed to login with username/password " + username + "/" + password); return; } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.ASCII_FILE_TYPE); } FileInputStream in = new FileInputStream(localPath); boolean result = ftpClient.storeFile(remotePath, in); if (!result) { Output.error("Logged in but failed to upload " + localPath + " to " + remotePath + "\nPerhaps one of the paths was wrong."); } in.close(); ftpClient.disconnect(); } catch (IOException ioe) { Output.error("Error ftp'ing using " + "\nlocalPath: " + localPath + "\nhostname: " + hostname + "\nusername: " + username + "\npassword: " + password + "\nremotePath: " + remotePath, ioe); } }
|
00
|
Code Sample 1:
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); } }
Code Sample 2:
public byte[] loadClassFirst(final String className) { if (className.startsWith("com.sun.sgs.impl.service.transaction.TransactionCoordinatorImpl")) { String resource = null; if (className.equals("com.sun.sgs.impl.service.transaction.TransactionCoordinatorImpl")) { resource = "com/sun/sgs/impl/service/transaction/TransactionCoordinatorImpl.class.bin"; } if (resource != null) { final URL url = Thread.currentThread().getContextClassLoader().getResource(resource); if (url != null) { try { return StreamUtil.read(url.openStream()); } catch (final IOException e) { } } throw new IllegalStateException("Unable to load binary class"); } } return null; }
|
11
|
Code Sample 1:
@Override public void fileUpload(UploadEvent uploadEvent) { FileOutputStream tmpOutStream = null; try { tmpUpload = File.createTempFile("projectImport", ".xml"); tmpOutStream = new FileOutputStream(tmpUpload); IOUtils.copy(uploadEvent.getInputStream(), tmpOutStream); panel.setGeneralMessage("Project file " + uploadEvent.getFileName() + " uploaded and ready for import."); } catch (Exception e) { panel.setGeneralMessage("Could not upload file: " + e); } finally { if (tmpOutStream != null) { IOUtils.closeQuietly(tmpOutStream); } } }
Code Sample 2:
public static void copyFile(IPath fromFileName, IPath toFileName) throws IOException { File fromFile = fromFileName.toFile(); File toFile = toFileName.toFile(); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } InputStream from = null; OutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(fromFile)); to = new BufferedOutputStream(new FileOutputStream(toFile)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
|
00
|
Code Sample 1:
public FTPClient getFTP(final Credentials credentials, final String remoteFile) throws NumberFormatException, SocketException, IOException, AccessDeniedException { String fileName = extractFilename(remoteFile); String fileDirectory = getPathName(remoteFile).substring(0, getPathName(remoteFile).indexOf(fileName)); FTPClient ftp; ftp = new FTPClient(); loadConfig(); logger.info("FTP connection to: " + extractHostname(remoteFile)); logger.info("FTP PORT: " + prop.getProperty("port")); ftp.connect(extractHostname(remoteFile), Integer.parseInt(prop.getProperty("port"))); int reply = ftp.getReplyCode(); if (!(FTPReply.isPositiveCompletion(reply))) { return null; } ftp.setFileTransferMode(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!ftp.login(credentials.getUserName(), credentials.getPassword())) { throw new AccessDeniedException(prop.getProperty("login_message")); } if (fileDirectory != null) { ftp.changeWorkingDirectory(fileDirectory); } return ftp; }
Code Sample 2:
public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
|
11
|
Code Sample 1:
public static boolean copyFile(File source, File dest) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } return true; }
Code Sample 2:
public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int 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 RobotList<Float> sort_incr_Float(RobotList<Float> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i)); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Float> sol = new RobotList<Float>(Float.class); for (int i = 0; i < length; i++) { sol.addLast(new Float(distri[i].value)); } return sol; }
Code Sample 2:
public static byte[] loadFile(File file) throws IOException { BufferedInputStream in = null; ByteArrayOutputStream sink = null; try { in = new BufferedInputStream(new FileInputStream(file)); sink = new ByteArrayOutputStream(); IOUtils.copy(in, sink); return sink.toByteArray(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(sink); } }
|
11
|
Code Sample 1:
@Override protected IStatus run(IProgressMonitor monitor) { final int BUFFER_SIZE = 1024; final int DISPLAY_BUFFER_SIZE = 8196; File sourceFile = new File(_sourceFile); File destFile = new File(_destFile); if (sourceFile.exists()) { try { Log.getInstance(FileCopierJob.class).debug(String.format("Start copy of %s to %s", _sourceFile, _destFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); monitor.beginTask(Messages.getString("FileCopierJob.MainTask") + " " + _sourceFile, (int) ((sourceFile.length() / DISPLAY_BUFFER_SIZE) + 4)); monitor.worked(1); byte[] buffer = new byte[BUFFER_SIZE]; int stepRead = 0; int read; boolean copying = true; while (copying) { read = bis.read(buffer); if (read > 0) { bos.write(buffer, 0, read); stepRead += read; } else { copying = false; } if (monitor.isCanceled()) { bos.close(); bis.close(); deleteFile(_destFile); return Status.CANCEL_STATUS; } if (stepRead >= DISPLAY_BUFFER_SIZE) { monitor.worked(1); stepRead = 0; } } bos.flush(); bos.close(); bis.close(); monitor.worked(1); } catch (Exception e) { processError("Error while copying: " + e.getMessage()); } Log.getInstance(FileCopierJob.class).debug("End of copy."); return Status.OK_STATUS; } else { processError(Messages.getString("FileCopierJob.ErrorSourceDontExists") + sourceFile.getAbsolutePath()); return Status.CANCEL_STATUS; } }
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; }
|
00
|
Code Sample 1:
private static void copyFile(String fromFile, String toFile) throws Exception { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
protected Object serveFile(MyServerSocket socket, String filenm, URL url) { PrintStream out = null; InputStream in = null; long len = 0; try { out = new PrintStream(socket.getOutputStream()); in = url.openStream(); len = in.available(); } catch (IOException e) { HttpHelper.httpWrap(HttpHelper.EXC, e.toString(), 0); } if (HttpHelper.isImage(filenm)) { out.print(HttpHelper.httpWrapPic(filenm, len)); } else if (filenm.endsWith(".html")) { Comms.copyStreamSED(in, out, MPRES); } else if (HttpHelper.isOtherFile(filenm)) { out.print(HttpHelper.httpWrapOtherFile(filenm, len)); } else { String type = MimeUtils.getMimeType(filenm); if (type.equals(MimeUtils.UNKNOWN_MIME_TYPE)) { out.print(HttpHelper.httpWrapMimeType(type, len)); } else { out.print(HttpHelper.httpWrapMimeType(type, len)); } } if (in == null) { Log.logThis("THE INPUT STREAM IS NULL...url=" + url); } else Files.copyStream(in, out); return null; }
|
00
|
Code Sample 1:
public <E extends Exception> void doWithConnection(String httpAddress, ICallableWithParameter<Void, URLConnection, E> toDo) throws E, ConnectionException { URLConnection connection; try { URL url = new URL(httpAddress); connection = url.openConnection(); } catch (MalformedURLException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } catch (IOException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } authenticationHandler.doWithProxyAuthentication(connection, toDo); }
Code Sample 2:
private void resolveFileDeclarations(Query query, Map<String, URL> sqlDeclarations) { Statement stmt = query.getStatement(); String fileDeclaration = stmt.getFile(); boolean hasFileDeclaration = fileDeclaration != null && !"".equals(fileDeclaration); if (hasFileDeclaration) { try { URL url = sqlDeclarations.get(stmt.getFile()); if (url != null) { URLConnection conn = url.openConnection(); InputStream input = conn.getInputStream(); String sqlDeclaration = StreamUtils.obtainStreamContents(input); stmt.setValue(sqlDeclaration); input.close(); } } catch (Exception e) { } } }
|
11
|
Code Sample 1:
public static void main(String[] args) { FileInputStream fr = null; FileOutputStream fw = null; BufferedInputStream br = null; BufferedOutputStream bw = null; try { fr = new FileInputStream("D:/5.xls"); fw = new FileOutputStream("c:/Dxw.java"); br = new BufferedInputStream(fr); bw = new BufferedOutputStream(fw); int read = br.read(); while (read != -1) { bw.write(read); read = br.read(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
public void guardarRecordatorio() { try { if (espaciosLlenos()) { guardarCantidad(); String dat = ""; String filenametxt = String.valueOf("recordatorio" + cantidadArchivos + ".txt"); String filenamezip = String.valueOf("recordatorio" + cantidadArchivos + ".zip"); cantidadArchivos++; dat += identificarDato(datoSeleccionado) + "\n"; dat += String.valueOf(mesTemporal) + "\n"; dat += String.valueOf(anoTemporal) + "\n"; dat += horaT.getText() + "\n"; dat += lugarT.getText() + "\n"; dat += actividadT.getText() + "\n"; File archivo = new File(filenametxt); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(dat); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filenamezip); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File(filenametxt); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry(filenametxt); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); JOptionPane.showMessageDialog(null, "El recordatorio ha sido guardado con exito", "Recordatorio Guardado", JOptionPane.INFORMATION_MESSAGE); marco.hide(); marco.dispose(); establecerMarca(); table.clearSelection(); } else JOptionPane.showMessageDialog(null, "Debe llenar los espacios de Hora, Lugar y Actividad", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
11
|
Code Sample 1:
public void shouldAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); }
Code Sample 2:
public static void readFile(FOUserAgent ua, String uri, OutputStream output) throws IOException { InputStream in = getURLInputStream(ua, uri); try { IOUtils.copy(in, output); } finally { IOUtils.closeQuietly(in); } }
|
00
|
Code Sample 1:
public void deleteSingle(String tbName, String idFld, String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (tbName == null || tbName.length() == 0 || id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delSQL = "delete from " + tbName + " where " + idFld + "='" + id + "'"; con.setAutoCommit(false); prepStmt = con.prepareStatement(delSQL); prepStmt.executeUpdate(); con.commit(); prepStmt.close(); con.close(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } }
Code Sample 2:
public static String md5(String plainText) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } ret = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ret; }
|
00
|
Code Sample 1:
public static void checkAndUpdateGameData() { new ErrThread() { @Override public void handledRun() throws Throwable { try { URL url = new URL(ONLINE_CLIENT_DATA + "gamedata.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); int lastversion = 0; String readHeader1 = br.readLine(); String readHeader2 = br.readLine(); String[] parts = readHeader2.split(" "); lastversion = new Integer(parts[1]); GameDatabase.loadVersion(); if (GameDatabase.version < lastversion) { Logger.log(LogTypes.LOG, "Downloading new gamedata"); BufferedOutputStream bo = null; File destfile = new File(GameDatabase.dataFilePath); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); bo.write((readHeader1 + "\n").getBytes()); bo.write((readHeader2 + "\n").getBytes()); int readedbyte; while ((readedbyte = br.read()) != -1) { bo.write(readedbyte); } bo.flush(); try { br.close(); bo.close(); } catch (Exception ex) { Logger.log(ex); } } } catch (java.net.UnknownHostException unknownHost) { Logger.log("Sourceforge is down, cannot update gamedata"); } catch (Exception e) { JOptionPane.showMessageDialog(FrameOrganizer.getClientFrame(), "The gamedata is outdated, but Coopnet couldn't update it!", "Gamedata outdated", JOptionPane.INFORMATION_MESSAGE); throw e; } finally { GameDatabase.loadVersion(); GameDatabase.load("", GameDatabase.dataFilePath); GameDatabase.detectGames(); } } }.start(); }
Code Sample 2:
private static boolean copyFile(File srcFile, File tagFile) throws IOException { if (srcFile == null || tagFile == null) { return false; } int length = 2097152; FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(tagFile); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); int i = 0; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); break; } if ((inC.size() - inC.position()) < 20971520) length = (int) (inC.size() - inC.position()); else length = 20971520; inC.transferTo(inC.position(), length, outC); inC.position(inC.position() + length); i++; } return true; }
|
00
|
Code Sample 1:
public void initializeWebInfo() throws MalformedURLException, IOException, DOMException { Tidy tidy = new Tidy(); URL url = new URL(YOUTUBE_URL + videoId); InputStream in = url.openConnection().getInputStream(); Document doc = tidy.parseDOM(in, null); Element e = doc.getDocumentElement(); String title = null; if (e != null && e.hasChildNodes()) { NodeList children = e.getElementsByTagName("title"); if (children != null) { for (int i = 0; i < children.getLength(); i++) { try { Element childE = (Element) children.item(i); if (childE.getTagName().equals("title")) { NodeList titleChildren = childE.getChildNodes(); for (int n = 0; n < titleChildren.getLength(); n++) { if (titleChildren.item(n).getNodeType() == childE.TEXT_NODE) { title = titleChildren.item(n).getNodeValue(); } } } } catch (Exception exp) { exp.printStackTrace(); } } } } if (title == null || title.equals("")) { throw new DOMException(DOMException.NOT_FOUND_ERR, "no title found"); } else { setTitle(title); } }
Code Sample 2:
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
@Override public void run() { File file; try { file = new File(filePath); if (!file.canWrite()) { Thread.sleep(5000); if (!file.canWrite()) { logger.error("Filed to gain write access to file:" + filePath); exitState = false; return; } } fis = new BufferedInputStream(new FileInputStream(filePath)); } catch (FileNotFoundException e) { logger.error("File not found:" + filePath); exitState = false; return; } catch (java.lang.InterruptedException ie) { logger.error("Upload thread halted or interrupted on file:" + filePath); exitState = false; return; } ftp = new FTPClient(); ftp.setDefaultTimeout(20 * 1000); boolean uploadSuccessful = false; try { ftp.enterLocalPassiveMode(); ftp.connect(ftpHostname); ftp.login(username, password); logger.trace("FTP Logged In and connected"); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { exitState = false; return; } ftp.setFileType(FTPClient.BINARY_FILE_TYPE); logger.trace("FTP Timeout Set and File Type Set"); ftp.changeWorkingDirectory(serverDirectory); ftp.storeUniqueFile(file.getName(), fis); logger.trace("File Uploaded"); if (FTPReply.isPositiveIntermediate(ftp.getReplyCode())) { System.out.println("Completing pending command"); ftp.completePendingCommand(); } uploadSuccessful = true; } catch (Exception e) { try { ftp.disconnect(); } catch (Exception de) { e.printStackTrace(); } logger.error("Error uploading file:", e); } finally { try { fis.close(); logger.trace("File closed"); ftp.logout(); logger.trace("FTP Logged Out"); ftp.disconnect(); logger.trace("FTP Disconnected"); if (uploadSuccessful) { logger.info("Deleting file:" + new File(filePath).getName()); if (!(new File(filePath)).delete()) { logger.error("Can't delete file for some reason"); } Thread.sleep(1000); exitState = true; return; } } catch (Exception e) { logger.error("Exception on file upload cleanup:", e); exitState = false; return; } } exitState = false; return; }
Code Sample 2:
public static void main(String[] args) { FTPClient f = new FTPClient(); String host = "ftpdatos.aemet.es"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); final String datestamp = sdf.format(new Date()); System.out.println(datestamp); String pathname = "datos_observacion/observaciones_diezminutales/" + datestamp + "_diezminutales/"; try { InetAddress server = InetAddress.getByName(host); f.connect(server); String username = "anonymous"; String password = "a@b.c"; f.login(username, password); FTPFile[] files = f.listFiles(pathname, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { return file.getName().startsWith(datestamp); } }); FTPFile file = files[files.length - 2]; f.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); boolean download = false; String remote = pathname + "/" + file.getName(); if (download) { File out = new File("/home/randres/Desktop/" + file.getName()); FileOutputStream fout = new FileOutputStream(out); System.out.println(f.retrieveFile(remote, fout)); fout.flush(); fout.close(); } else { GZIPInputStream gzipin = new GZIPInputStream(f.retrieveFileStream(remote)); LineNumberReader lreader = new LineNumberReader(new InputStreamReader(gzipin, "Cp1250")); String line = null; while ((line = lreader.readLine()) != null) { Aeminuto.processLine(line); } lreader.close(); } f.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void xtest2() throws Exception { InputStream input1 = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream input2 = new FileInputStream("C:/Documentos/j931_02.pdf"); InputStream tmp = new ITextManager().merge(new InputStream[] { input1, input2 }); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input1.close(); input2.close(); tmp.close(); output.close(); }
Code Sample 2:
protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
|
00
|
Code Sample 1:
private static void loadEmoticons() { emoticons = new Hashtable(); URL url = ChatPanel.class.getResource("/resources/text/emoticon.properties"); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = br.readLine()) != null) { if (line.trim().length() == 0 || line.charAt(0) == '#') continue; int i0 = line.indexOf('='); if (i0 != -1) { String key = line.substring(0, i0).trim(); String value = line.substring(i0 + 1).trim(); value = StringUtil.replaceString(value, "\\n", "\n"); URL eUrl = ChatPanel.class.getResource("/resources/emoticon/" + value); if (eUrl != null) emoticons.put(key, new ImageIcon(eUrl)); } } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { } } } }
Code Sample 2:
public static void main(String[] args) { FTPClient f = new FTPClient(); String host = "ftpdatos.aemet.es"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); final String datestamp = sdf.format(new Date()); System.out.println(datestamp); String pathname = "datos_observacion/observaciones_diezminutales/" + datestamp + "_diezminutales/"; try { InetAddress server = InetAddress.getByName(host); f.connect(server); String username = "anonymous"; String password = "a@b.c"; f.login(username, password); FTPFile[] files = f.listFiles(pathname, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { return file.getName().startsWith(datestamp); } }); FTPFile file = files[files.length - 2]; f.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); boolean download = false; String remote = pathname + "/" + file.getName(); if (download) { File out = new File("/home/randres/Desktop/" + file.getName()); FileOutputStream fout = new FileOutputStream(out); System.out.println(f.retrieveFile(remote, fout)); fout.flush(); fout.close(); } else { GZIPInputStream gzipin = new GZIPInputStream(f.retrieveFileStream(remote)); LineNumberReader lreader = new LineNumberReader(new InputStreamReader(gzipin, "Cp1250")); String line = null; while ((line = lreader.readLine()) != null) { Aeminuto.processLine(line); } lreader.close(); } f.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
private static void generateTIFF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException { Debug.println("ImageCropper.generateTIFF begin"); MapContext map_context = new MapContext("test", new Configuration()); try { Map map = new Map(map_context, area_label, new Configuration()); map.setCoordSys(ProjectionCategories.default_coordinate_system); map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white))); String type = null; RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename)); map.addLayer(rlayer, true); map.setBounds2DImage(bounds, true); Dimension image_dim = null; image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1); if (output_maximum_size > 0) { double width_factor = image_dim.getWidth() / output_maximum_size; double height_factor = image_dim.getHeight() / output_maximum_size; double factor = Math.max(width_factor, height_factor); if (factor > 1.0) { image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor); } } map.setImageDimension(image_dim); map.scale(); image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight()); Image image = null; Graphics gr = null; image = ImageCreator.getImage(image_dim); gr = image.getGraphics(); try { map.paint(gr); } catch (Exception e) { Debug.println("map.paint error: " + e.getMessage()); } String tiff_filename = ""; try { tiff_filename = formatPath(category, timeseries, output_filename); new File(new_filename).mkdirs(); Debug.println("tiff_filename: " + tiff_filename); BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED); bi.createGraphics().drawImage(image, 0, 0, null); File f = new File(tiff_filename); FileOutputStream out = new FileOutputStream(f); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS); TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param); encoder.encode(bi); out.close(); } catch (IOException e) { Debug.println("ImageCropper.generateTIFF TIFFCodec e: " + e.getMessage()); throw new IOException("GenerateTIFF.IOException: " + e); } PreparedStatement pstmt = null; try { String query = "select Proj_ID, AccessType_Code from project " + "where Proj_Code= '" + area_code.trim() + "'"; Statement stmt = null; ResultSet rs = null; int proj_id = -1; int access_code = -1; stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { proj_id = rs.getInt(1); access_code = rs.getInt(2); } rs.close(); stmt.close(); String delete_raster = "delete from rasterlayer where " + "Raster_Name='" + tiff_name.trim() + "' and Group_Code='" + category.trim() + "' and Proj_ID =" + proj_id; Debug.println("***** delete_raster: " + delete_raster); pstmt = con.prepareStatement(delete_raster); boolean del = pstmt.execute(); pstmt.close(); String insert_raster = "insert into rasterlayer(Raster_Name, " + "Group_Code, Proj_ID, Raster_TimeCode, Raster_Xmin, " + "Raster_Ymin, Raster_Area_Xmin, Raster_Area_Ymin, " + "Raster_Visibility, Raster_Order, Raster_Path, " + "AccessType_Code, Raster_TimePeriod) values(?,?,?,?, " + "?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(insert_raster); pstmt.setString(1, tiff_name); pstmt.setString(2, category); pstmt.setInt(3, proj_id); pstmt.setString(4, timeseries); pstmt.setDouble(5, raster_bounds.getX()); pstmt.setDouble(6, raster_bounds.getY()); pstmt.setDouble(7, raster_bounds.getWidth()); pstmt.setDouble(8, raster_bounds.getHeight()); pstmt.setString(9, "false"); int sequence = 0; if (tiff_name.endsWith("DP")) { sequence = 1; } else if (tiff_name.endsWith("DY")) { sequence = 2; } else if (tiff_name.endsWith("DA")) { sequence = 3; } pstmt.setInt(10, sequence); pstmt.setString(11, tiff_filename); pstmt.setInt(12, access_code); if (time == null) { pstmt.setNull(13, java.sql.Types.DATE); } else { pstmt.setDate(13, new java.sql.Date(time.getTimeInMillis())); } pstmt.executeUpdate(); } catch (SQLException e) { Debug.println("SQLException occurred e: " + e.getMessage()); con.rollback(); throw new SQLException("GenerateTIFF.SQLException: " + e); } finally { pstmt.close(); } } catch (Exception e) { Debug.println("ImageCropper.generateTIFF e: " + e.getMessage()); } Debug.println("ImageCropper.generateTIFF end"); }
Code Sample 2:
public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); }
|
11
|
Code Sample 1:
public String loadFileContent(final String _resourceURI) { final Lock readLock = this.fileLock.readLock(); final Lock writeLock = this.fileLock.writeLock(); boolean hasReadLock = false; boolean hasWriteLock = false; try { readLock.lock(); hasReadLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { readLock.unlock(); hasReadLock = false; writeLock.lock(); hasWriteLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI); final StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); } catch (final IOException ex) { throw new IllegalStateException("Resource not read-able", ex); } final String loadedResource = writer.toString(); this.cachedResources.put(_resourceURI, loadedResource); } writeLock.unlock(); hasWriteLock = false; readLock.lock(); hasReadLock = true; } return this.cachedResources.get(_resourceURI); } finally { if (hasReadLock) { readLock.unlock(); } if (hasWriteLock) { writeLock.unlock(); } } }
Code Sample 2:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
|
11
|
Code Sample 1:
public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); }
Code Sample 2:
public static String hash(String str) { MessageDigest summer; try { summer = MessageDigest.getInstance("md5"); summer.update(str.getBytes()); } catch (NoSuchAlgorithmException ex) { return null; } BigInteger hash = new BigInteger(1, summer.digest()); String hashword = hash.toString(16); return hashword; }
|
11
|
Code Sample 1:
@Override public RoleItem addUserRole(RoleItem role, long userId) throws DatabaseException { if (role == null) throw new NullPointerException("role"); if (role.getName() == null || "".equals(role.getName())) throw new NullPointerException("role.getName()"); if (hasRole(role.getName(), userId)) { return new RoleItem(role.getName(), "", "exist"); } RoleItem defaultRole = new RoleItem(role.getName(), "", "exist"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; String roleDesc = ""; PreparedStatement seqSt = null, roleDescSt = null; try { int modified = 0; PreparedStatement insSt = getConnection().prepareStatement(INSERT_USER_IN_ROLE_STATEMENT); insSt.setLong(1, userId); insSt.setString(2, role.getName()); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_ROLE_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } roleDescSt = getConnection().prepareStatement(SELECT_ROLE_DESCRIPTION); roleDescSt.setString(1, role.getName()); ResultSet rs2 = roleDescSt.executeQuery(); while (rs2.next()) { roleDesc = rs2.getString(1); } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } defaultRole.setId(retID); defaultRole.setDescription(roleDesc); return defaultRole; }
Code Sample 2:
public Long createSite(Site site, List<String> hosts) { if (log.isDebugEnabled()) { log.debug("site: " + site); if (site != null) { log.debug(" language: " + site.getDefLanguage()); log.debug(" country: " + site.getDefCountry()); log.debug(" variant: " + site.getDefVariant()); log.debug(" companyId: " + site.getCompanyId()); } } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_PORTAL_LIST_SITE"); seq.setTableName("WM_PORTAL_LIST_SITE"); seq.setColumnName("ID_SITE"); Long siteId = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_PORTAL_LIST_SITE (" + "ID_SITE, ID_FIRM, DEF_LANGUAGE, DEF_COUNTRY, DEF_VARIANT, " + "NAME_SITE, ADMIN_EMAIL, IS_CSS_DYNAMIC, CSS_FILE, " + "IS_REGISTER_ALLOWED " + ")values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, siteId); RsetTools.setLong(ps, num++, site.getCompanyId()); ps.setString(num++, site.getDefLanguage()); ps.setString(num++, site.getDefCountry()); ps.setString(num++, site.getDefVariant()); ps.setString(num++, site.getSiteName()); ps.setString(num++, site.getAdminEmail()); ps.setInt(num++, site.getCssDynamic() ? 1 : 0); ps.setString(num++, site.getCssFile()); ps.setInt(num++, site.getRegisterAllowed() ? 1 : 0); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); if (hosts != null) { for (String s : hosts) { VirtualHost host = new VirtualHostBean(null, siteId, s); InternalDaoFactory.getInternalVirtualHostDao().createVirtualHost(dbDyn, host); } } dbDyn.commit(); return siteId; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new site"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
00
|
Code Sample 1:
public static Set<Address> getDatosCatastrales(String pURL) { Set<Address> result = new HashSet<Address>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniInm1 = "<rcdnp>"; String finInm1 = "</rcdnp>"; String iniInm2 = "<bi>"; String finInm2 = "</bi>"; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniCar = "<car>"; String finCar = "</car>"; String iniCC1 = "<cc1>"; String finCC1 = "</cc1>"; String iniCC2 = "<cc2>"; String finCC2 = "</cc2>"; String iniLDT = "<ldt>"; String iniBq = "<bq>"; String finBq = "</bq>"; String iniEs = "<es>"; String finEs = "</es>"; String iniPt = "<pt>"; String finPt = "</pt>"; String iniPu = "<pu>"; String finPu = "</pu>"; boolean error = false; int ini, fin; int postal = 0; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniInm1) || str.contains(iniInm2)) { Address inmueble = new Address(); while ((str = br.readLine()) != null && !str.contains(finInm1) && !str.contains(finInm2)) { if (str.contains(iniPC1) && str.contains(finPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); inmueble.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2) && str.contains(finPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniLDT) && str.contains("-")) { postal = Integer.parseInt(str.substring(str.lastIndexOf("-") - 5, str.lastIndexOf("-"))); } if (str.contains(iniCar) && str.contains(finCar)) { ini = str.indexOf(iniCar) + iniCar.length(); fin = str.indexOf(finCar); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC1) && str.contains(finCC1)) { ini = str.indexOf(iniCC1) + iniCC1.length(); fin = str.indexOf(finCC1); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC2) && str.contains(finCC2)) { ini = str.indexOf(iniCC2) + iniCC2.length(); fin = str.indexOf(finCC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniBq) && str.contains(finBq)) { ini = str.indexOf(iniBq) + iniBq.length(); fin = str.indexOf(finBq); inmueble.setBlock(str.substring(ini, fin)); } if (str.contains(iniEs) && str.contains(finEs)) { ini = str.indexOf(iniEs) + iniEs.length(); fin = str.indexOf(finEs); inmueble.setStairs(str.substring(ini, fin)); } if (str.contains(iniPt) && str.contains(finPt)) { ini = str.indexOf(iniPt) + iniPt.length(); fin = str.indexOf(finPt); inmueble.setFloor(str.substring(ini, fin)); } if (str.contains(iniPu) && str.contains(finPu)) { ini = str.indexOf(iniPu) + iniPu.length(); fin = str.indexOf(finPu); inmueble.setDoor(str.substring(ini, fin)); } } result.add(inmueble); } } } br.close(); if (result.size() == 1) { Object ad[] = result.toArray(); Coordinate coord = ConversorCoordenadas.getCoordenadas(((Address) ad[0]).getDescription()); coord.setPostcode(postal); for (Address inm : result) inm.setCoodinate(coord); } } catch (Exception e) { System.err.println(e); } return result; }
Code Sample 2:
public static InputStream getInputStream(URL url) throws IOException { if (url.getProtocol().equals("file")) { String path = decode(url.getPath(), "UTF-8"); return new BufferedInputStream(new FileInputStream(path)); } else { return new BufferedInputStream(url.openStream()); } }
|
11
|
Code Sample 1:
public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { final ServletOutputStream outputStream = res.getOutputStream(); if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; if (ByteArrayInputStream.class.isAssignableFrom(r.getClass())) res.addHeader("Content-Length", Integer.toString(in.available())); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } outputStream.flush(); } }
Code Sample 2:
public File takeFile(File f, String prefix, String suffix) throws IOException { File nf = createNewFile(prefix, suffix); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); FileOutputStream fos = new FileOutputStream(nf); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); f.delete(); return nf; }
|
11
|
Code Sample 1:
private static BufferedInputStream getHTTPConnection(String sUrl) { URL url = null; BufferedInputStream bis = null; try { url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setConnectTimeout(30000); connection.setReadTimeout(60000); connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); connection.connect(); String encoding = connection.getContentEncoding(); if (!Utilities.isEmpty(encoding) && "gzip".equalsIgnoreCase(encoding)) { bis = new BufferedInputStream(new GZIPInputStream(connection.getInputStream()), IO_BUFFER_SIZE); } else if (!Utilities.isEmpty(encoding) && "deflate".equalsIgnoreCase(encoding)) { bis = new BufferedInputStream(new InflaterInputStream(connection.getInputStream(), new Inflater(true)), IO_BUFFER_SIZE); } else { bis = new BufferedInputStream(connection.getInputStream(), IO_BUFFER_SIZE); } } catch (Exception e) { LogUtil.e(Constants.TAG, e.getMessage()); } return bis; }
Code Sample 2:
public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
|
00
|
Code Sample 1:
private String buildShaHashOf(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(source.getBytes()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } }
Code Sample 2:
private boolean goToForum() { URL url = null; URLConnection urlConn = null; int code = 0; boolean gotNumReplies = false; boolean gotMsgNum = false; try { url = new URL("http://" + m_host + "/forums/index.php?topic=" + m_gameId + ".new"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(false); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); m_referer = url.toString(); readCookies(urlConn); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code != 200) { String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = ""; Pattern p_numReplies = Pattern.compile(".*?;num_replies=(\\d+)\".*"); Pattern p_msgNum = Pattern.compile(".*?<a name=\"msg(\\d+)\"></a><a name=\"new\"></a>.*"); Pattern p_attachId = Pattern.compile(".*?action=dlattach;topic=" + m_gameId + ".0;attach=(\\d+)\">.*"); while ((line = in.readLine()) != null) { if (!gotNumReplies) { Matcher match_numReplies = p_numReplies.matcher(line); if (match_numReplies.matches()) { m_numReplies = match_numReplies.group(1); gotNumReplies = true; continue; } } if (!gotMsgNum) { Matcher match_msgNum = p_msgNum.matcher(line); if (match_msgNum.matches()) { m_msgNum = match_msgNum.group(1); gotMsgNum = true; continue; } } Matcher match_attachId = p_attachId.matcher(line); if (match_attachId.matches()) m_attachId = match_attachId.group(1); } in.close(); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotNumReplies || !gotMsgNum) { m_turnSummaryRef = "Error: "; if (!gotNumReplies) m_turnSummaryRef += "No num_replies found in A&A.org forum topic. "; if (!gotMsgNum) m_turnSummaryRef += "No msgXXXXXX found in A&A.org forum topic. "; return false; } return true; }
|
11
|
Code Sample 1:
private void copy(File source, File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { close(in); close(out); } }
Code Sample 2:
public static void copyFile(File source, File dest) throws Exception { FileInputStream fis = new FileInputStream(source); try { FileOutputStream fos = new FileOutputStream(dest); try { int read = fis.read(); while (read != -1) { fos.write(read); read = fis.read(); } } finally { fos.close(); } } finally { fis.close(); } }
|
00
|
Code Sample 1:
private void downloadFile(File file, String url) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); final FileOutputStream outStream = new FileOutputStream(file); out = new BufferedOutputStream(outStream, IO_BUFFER_SIZE); byte[] bytes = new byte[IO_BUFFER_SIZE]; while (in.read(bytes) > 0) { out.write(bytes); } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Code Sample 2:
private synchronized void createFTPConnection() throws FTPBrowseException { ftpClient = new FTPClient(); try { InetAddress inetAddress = InetAddress.getByName(url.getHost()); if (url.getPort() == -1) { ftpClient.connect(inetAddress); } else { ftpClient.connect(inetAddress, url.getPort()); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new FTPBrowseException(ftpClient.getReplyString()); } if (null != passwordAuthentication) { ftpClient.login(passwordAuthentication.getUserName(), new StringBuffer().append(passwordAuthentication.getPassword()).toString()); } if (url.getPath().length() > 0) { ftpClient.changeWorkingDirectory(url.getPath()); } homeDirectory = ftpClient.printWorkingDirectory(); } catch (UnknownHostException e) { throw new FTPBrowseException(e.getMessage()); } catch (SocketException e) { throw new FTPBrowseException(e.getMessage()); } catch (FTPBrowseException e) { throw e; } catch (IOException e) { throw new FTPBrowseException(e.getMessage()); } }
|
11
|
Code Sample 1:
public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public List tree(String cat, int branch) { Pattern p = Pattern.compile("<a href=\"javascript:checkBranch\\(([0-9]+), 'true'\\)\">([^<]*)</a>"); Matcher m; List res = new ArrayList(); URL url; HttpURLConnection conn; System.out.println(); try { url = new URL("http://cri-srv-ade.insa-toulouse.fr:8080/ade/standard/gui/tree.jsp?category=trainee&expand=false&forceLoad=false&reload=false&scroll=0"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Cookie", sessionId); BufferedReader i = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = i.readLine()) != null) { m = p.matcher(line); if (m.find()) { trainee.add(new Node(Integer.parseInt(m.group(1)), m.group(2))); System.out.println(m.group(1) + " - " + m.group(2)); } } } catch (Exception e2) { e2.printStackTrace(); } return res; }
Code Sample 2:
public static byte[] readHTTPFile(String url, StringBuffer contentType, StringBuffer encoding) { try { URL u = new URL(url); URLConnection urlConn = u.openConnection(); urlConn.setReadTimeout(10 * 1000); urlConn.setConnectTimeout(10 * 1000); urlConn.setDoInput(true); urlConn.setDoOutput(false); String status = urlConn.getHeaderField(null).toLowerCase(); String location = urlConn.getHeaderField("Location"); String cookie = urlConn.getHeaderField("Set-Cookie"); int times = 0; while ((status.indexOf("http/1.1 3") >= 0 || status.indexOf("http/1.0 3") >= 0) && !HelperStd.isEmpty(location)) { if (!HelperStd.isEmpty(urlConn.getHeaderField("Set-Cookie"))) cookie = urlConn.getHeaderField("Set-Cookie"); u = new URL(location); urlConn = u.openConnection(); urlConn.setReadTimeout(10 * 1000); urlConn.setConnectTimeout(10 * 1000); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setRequestProperty("Cookie", cookie); status = urlConn.getHeaderField(null).toLowerCase(); location = urlConn.getHeaderField("Location"); times++; if (times > 10) break; } System.out.println(urlConn.getHeaderField(null) + ":" + urlConn.getContentLength() + ":" + u); if (contentType != null) contentType.append(urlConn.getContentType()); if (encoding != null) { String enc = null, ct = urlConn.getContentType(); if (ct != null && ct.indexOf("charset=") > 0) { int a = ct.indexOf("charset=") + "charset=".length(); enc = ct.substring(a); } if (enc == null) enc = urlConn.getContentEncoding(); if (enc == null) enc = "ISO-8859-1"; encoding.append(enc); } BufferedInputStream in = new BufferedInputStream(urlConn.getInputStream()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int read = 0; while (read != -1) { read = in.read(b); if (read > 0) bout.write(b, 0, read); } in.close(); System.out.println(bout.size()); return bout.toByteArray(); } catch (Exception e) { e.printStackTrace(); System.out.println("readHTTPFile:" + e.getMessage() + "," + url); } return new byte[0]; }
|
00
|
Code Sample 1:
public APIResponse create(User user) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/user/create").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(user, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Create User Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
Code Sample 2:
public void cleanup(long timeout) throws PersisterException { long threshold = System.currentTimeMillis() - timeout; Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("delete from " + _table_name + " where " + _ts_col + " < ?"); ps.setLong(1, threshold); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to cleanup timed out objects: ", th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
|
00
|
Code Sample 1:
public void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } button.setEnabled(true); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
@Override public void action(String msg, String uri, Gateway gateway) throws Exception { String city = "成都"; if (msg.indexOf("#") != -1) { city = msg.substring(msg.indexOf("#") + 1); } String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode={city}&theUserID="; url = url.replace("{city}", URLEncoder.encode(city, "UTF8")); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (conn.getResponseCode() == 200) { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(conn.getInputStream()); List strings = doc.getRootElement().getChildren(); String[] sugguestions = getText(strings.get(6)).split("\n"); StringBuffer buffer = new StringBuffer(); buffer.append("欢迎使用MapleSMS的天气服务!\n"); buffer.append("你查询的是 " + getText(strings.get(1)) + "的天气。\n"); buffer.append(getText(strings.get(4)) + "。\n"); buffer.append(getText(strings.get(5)) + "。\n"); buffer.append(sugguestions[0] + "\n"); buffer.append(sugguestions[1] + "\n"); buffer.append(sugguestions[7] + "\n"); buffer.append("感谢你使用MapleSMS的天气服务!祝你愉快!"); gateway.sendSMS(uri, buffer.toString()); } else { gateway.sendSMS(uri, "对不起,你输入的城市格式有误,请检查后再试~"); } }
Code Sample 2:
public static String calcCRC(String phrase) { StringBuffer crcCalc = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(phrase.getBytes()); byte[] tabDigest = md.digest(); for (int i = 0; i < tabDigest.length; i++) { String octet = "0" + Integer.toHexString(tabDigest[i]); crcCalc.append(octet.substring(octet.length() - 2)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crcCalc.toString(); }
|
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:
private void forcedCopy(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
public Web(String urlString, String charset) throws java.net.MalformedURLException, java.io.IOException { this.charset = charset; final java.net.URL url = new java.net.URL(urlString); final java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) throw new java.lang.IllegalArgumentException("URL protocol must be HTTP."); final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(600000); conn.setReadTimeout(600000); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-agent", "spider"); conn.connect(); responseHeader = conn.getHeaderFields(); responseCode = conn.getResponseCode(); responseURL = conn.getURL(); length = conn.getContentLength(); final java.io.InputStream stream = conn.getErrorStream(); if (stream != null) { content = readStream(length, stream); } else if ((inputStream = conn.getContent()) != null && inputStream instanceof java.io.InputStream) { content = readStream(length, (java.io.InputStream) inputStream); } conn.disconnect(); }
Code Sample 2:
public static void main(final String[] args) { final Runnable startDerby = new Runnable() { public void run() { try { final NetworkServerControl control = new NetworkServerControl(InetAddress.getByName("localhost"), 1527); control.start(new PrintWriter(System.out)); } catch (final Exception ex) { throw new RuntimeException(ex); } } }; new Thread(startDerby).start(); final Runnable startActiveMq = new Runnable() { public void run() { Main.main(new String[] { "start", "xbean:file:active-mq-config.xml" }); } }; new Thread(startActiveMq).start(); final Runnable startMailServer = new Runnable() { public void run() { final SimpleMessageListener listener = new SimpleMessageListener() { public final boolean accept(final String from, final String recipient) { return true; } public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } } }; final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(listener)); smtpServer.start(); System.out.println("Started SMTP Server"); } }; new Thread(startMailServer).start(); }
|
11
|
Code Sample 1:
void run(String[] args) { InputStream istream = System.in; System.out.println("TradeMaximizer " + version); String filename = parseArgs(args, false); if (filename != null) { System.out.println("Input from: " + filename); try { if (filename.startsWith("http:") || filename.startsWith("ftp:")) { URL url = new URL(filename); istream = url.openStream(); } else istream = new FileInputStream(filename); } catch (IOException ex) { fatalError(ex.toString()); } } List<String[]> wantLists = readWantLists(istream); if (wantLists == null) return; if (options.size() > 0) { System.out.print("Options:"); for (String option : options) System.out.print(" " + option); System.out.println(); } System.out.println(); try { MessageDigest digest = MessageDigest.getInstance("MD5"); for (String[] wset : wantLists) { for (String w : wset) { digest.update((byte) ' '); digest.update(w.getBytes()); } digest.update((byte) '\n'); } System.out.println("Input Checksum: " + toHexString(digest.digest())); } catch (NoSuchAlgorithmException ex) { } parseArgs(args, true); if (iterations > 1 && seed == -1) { seed = System.currentTimeMillis(); System.out.println("No explicit SEED, using " + seed); } if (!(metric instanceof MetricSumSquares) && priorityScheme != NO_PRIORITIES) System.out.println("Warning: using priorities with the non-default metric is normally worthless"); buildGraph(wantLists); if (showMissing && officialNames != null && officialNames.size() > 0) { for (String name : usedNames) officialNames.remove(name); List<String> missing = new ArrayList<String>(officialNames); Collections.sort(missing); for (String name : missing) { System.out.println("**** Missing want list for official name " + name); } System.out.println(); } if (showErrors && errors.size() > 0) { Collections.sort(errors); System.out.println("ERRORS:"); for (String error : errors) System.out.println(error); System.out.println(); } long startTime = System.currentTimeMillis(); graph.removeImpossibleEdges(); List<List<Graph.Vertex>> bestCycles = graph.findCycles(); int bestMetric = metric.calculate(bestCycles); if (iterations > 1) { System.out.println(metric); graph.saveMatches(); for (int i = 0; i < iterations - 1; i++) { graph.shuffle(); List<List<Graph.Vertex>> cycles = graph.findCycles(); int newMetric = metric.calculate(cycles); if (newMetric < bestMetric) { bestMetric = newMetric; bestCycles = cycles; graph.saveMatches(); System.out.println(metric); } else if (verbose) System.out.println("# " + metric); } System.out.println(); graph.restoreMatches(); } long stopTime = System.currentTimeMillis(); displayMatches(bestCycles); if (showElapsedTime) System.out.println("Elapsed time = " + (stopTime - startTime) + "ms"); }
Code Sample 2:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException, WrongFormatException, URISyntaxException { System.out.println(new URI("google.com.ua.css").toString()); Scanner scc = new Scanner(System.in); System.err.print(scc.nextLine().substring(1)); ServerSocket s = new ServerSocket(5354); while (true) { Socket client = s.accept(); InputStream iStream = client.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(iStream)); String line = ""; while (!(line = bf.readLine()).equals("")) { System.out.println(line); } System.out.println("end of request"); new PrintWriter(client.getOutputStream()).println("hi"); bf.close(); } }
Code Sample 2:
public void transform(File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException { FileChannel original = new FileInputStream(inputMatrixFile).getChannel(); FileChannel copy = new FileOutputStream(outputMatrixFile).getChannel(); copy.transferFrom(original, 0, original.size()); original.close(); copy.close(); }
|
00
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public ByteArrayOutputStream download(final String contentUuid) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } inputStream.close(); return outputStream; } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } }
|
00
|
Code Sample 1:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ejb.bprocess.OAIPMH.AutoHarvesterSession ahSession = home.create(); java.util.Vector vector = new java.util.Vector(1, 1); Integer libraryId = new Integer(1); String xmlstr = ""; String str = ""; String arr[] = new String[2]; String[] subarr = new String[4]; String mdPrefix = "", mdPrefixValue = ""; String from = "", fromValue = ""; String until = "", untilValue = ""; String set = "", setValue = ""; String oai_pmhRequest = request.getParameter("verb"); String oai_pmhQuery = request.getQueryString(); String urlStr = ""; urlStr = "http://" + request.getServerName() + ":" + request.getServerPort() + "/newgenlibctxt/HarvestServlet"; String attribute = oai_pmhQuery; String arguments = attribute.substring(attribute.indexOf("?") + 1); StringTokenizer st = new StringTokenizer(arguments, "&"); int i = 0; int j = 0; int z = 0; int count = 0; String type = ""; while (st.hasMoreTokens()) { arr[i] = st.nextToken(); StringTokenizer subst = new StringTokenizer(arr[i], "="); while (subst.hasMoreTokens()) { subarr[j] = subst.nextToken(); j++; } i++; count++; } int mdfCount = 0, fromCount = 0, untilCount = 0, setCount = 0; ListRecords lr = new ListRecords(); for (int k = 0; k < j; k += 2) { if (subarr[k].equals("from")) { from = "from"; fromCount++; fromValue = subarr[k + 1]; fromValue = lr.validateDate(fromValue); } else if (subarr[k].equals("until")) { until = "until"; untilCount++; untilValue = subarr[k + 1]; untilValue = lr.validateDate(untilValue); } } if (fromValue.equals("") && untilCount == 1) { fromValue = lr.validateDate("0001-01-01"); } else if (untilValue.equals("") && fromCount == 1) { String a = (new Resdate()).getDate(); untilValue = a.substring(0, a.indexOf("T")); } System.out.println("This is fromValue:" + fromValue); System.out.println("This is untilValue:" + untilValue); vector = ahSession.getHarvestLibrary(null, libraryId); String harlibraryId = ""; if (vector.size() > 0) { for (int k = 0; k < vector.size(); k = k + 3) { harlibraryId = vector.elementAt(k).toString(); String harvesturl = vector.elementAt(k + 1).toString(); String status = vector.elementAt(k + 2).toString(); if (status.equals("A")) { String oai_pmhRequest1 = request.getParameter("verb"); String oai_pmhQuery1 = request.getQueryString(); urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&metadataPrefix=marc21&from=" + fromValue + "&until=" + untilValue + ""; boolean resExists = true; for (int n = 0; resExists == true; n++) { java.net.URL url = new java.net.URL(urlStr); java.net.URLConnection urlCon = url.openConnection(); urlCon.setDoInput(true); urlCon.connect(); InputStream is = urlCon.getInputStream(); System.out.println("input" + is.available()); org.jdom.input.SAXBuilder sb = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = sb.build(is); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc); System.out.println("xmlStr:" + xmlstr); doc = null; sb = null; java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); String resT = doc.getRootElement().getChildText("resumptionToken", doc.getRootElement().getNamespace()); if (!(resT == null)) { urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&resumptionToken=" + resT; } else { resExists = false; } } } else if (status.equals("B")) { java.io.File file = new java.io.File(harvesturl); java.io.File[] file1 = file.listFiles(); for (int b = 0; b < file1.length; b++) { File file2 = (File) file1[b]; System.out.println("File2:" + file2); long lastmodifed = file2.lastModified(); StringTokenizer st1 = new StringTokenizer(fromValue, "-"); String dar[] = new String[3]; java.util.Calendar c1 = java.util.Calendar.getInstance(); int g = 0; while (st1.hasMoreElements()) { dar[g] = st1.nextToken(); g++; } c1.set(Integer.parseInt(dar[0]), Integer.parseInt(dar[1]), Integer.parseInt(dar[2])); StringTokenizer st2 = new StringTokenizer(untilValue, "-"); String dar1[] = new String[3]; java.util.Calendar c2 = java.util.Calendar.getInstance(); int d = 0; while (st2.hasMoreElements()) { dar1[d] = st2.nextToken(); d++; } c2.set(Integer.parseInt(dar1[0]), Integer.parseInt(dar1[1]), Integer.parseInt(dar1[2])); java.util.Calendar c3 = java.util.Calendar.getInstance(); c3.setTimeInMillis(lastmodifed); c3.set(java.util.Calendar.HOUR, 0); c3.set(java.util.Calendar.AM_PM, java.util.Calendar.AM); c3.set(java.util.Calendar.MINUTE, 0); c3.set(java.util.Calendar.SECOND, 0); c3.set(java.util.Calendar.MILLISECOND, 0); java.util.Date d1 = c1.getTime(); java.util.Date d2 = c2.getTime(); java.util.Date d3 = c3.getTime(); System.out.println("This is d1:" + d1); System.out.println("This is d2:" + d2); System.out.println("This is d3:" + d3); if (d3.after(d1) && d3.before(d2)) { org.jdom.input.SAXBuilder sb1 = new org.jdom.input.SAXBuilder(); org.jdom.Document doc1 = sb1.build(new java.io.FileInputStream(file2)); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc1); java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); } } } } } } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } out.setLastModified(in.lastModified()); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String isbn = null; HttpGet get = null; while ((isbn = br.readLine().split(" ")[0]) != null) { System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn)); get = new HttpGet(String.format(isbnSearchUrl, isbn)); HttpResponse resp = httpclient.execute(get); Scanner s = new Scanner(resp.getEntity().getContent()); String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0); if (pattern != null) { MatchResult match = s.match(); if (match.groupCount() == 3) { if (match.group(2) == null) { System.out.println(isbn + ": copies available"); } else { System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies"); } } } else { System.out.println(isbn + ": no match"); } get.abort(); } }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public static File copyFile(File from, File to) throws IOException { FileOutputStream fos = new FileOutputStream(to); FileInputStream fis = new FileInputStream(from); FileChannel foc = fos.getChannel(); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return to; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
|
11
|
Code Sample 1:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("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) { ; } } }
Code Sample 2:
private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; }
|
00
|
Code Sample 1:
public void callBatch(final List<JsonRpcClient.Call> calls, final JsonRpcClient.BatchCallback callback) { HttpPost httpPost = new HttpPost(mRpcUrl); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try { for (int i = 0; i < calls.size(); i++) { JsonRpcClient.Call call = calls.get(i); JSONObject callJson = new JSONObject(); callJson.put("method", call.getMethodName()); if (call.getParams() != null) { JSONObject callParams = (JSONObject) call.getParams(); @SuppressWarnings("unchecked") Iterator<String> keysIterator = callParams.keys(); String key; while (keysIterator.hasNext()) { key = keysIterator.next(); callJson.put(key, callParams.get(key)); } } callsJson.put(i, callJson); } requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "POST request: " + requestJson.toString()); } } catch (JSONException e) { } catch (UnsupportedEncodingException e) { } try { HttpResponse httpResponse = mHttpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "POST response: " + sb.toString()); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); Object[] resultData = new Object[calls.size()]; for (int i = 0; i < calls.size(); i++) { JSONObject result = resultsJson.getJSONObject(i); if (result.has("error")) { callback.onError(i, new JsonRpcException((int) result.getInt("error"), calls.get(i).getMethodName(), result.getString("message"), null)); resultData[i] = null; } else { resultData[i] = result.get("data"); } } callback.onData(resultData); } else { callback.onError(-1, new JsonRpcException(-1, "Received HTTP status code other than HTTP 2xx: " + httpResponse.getStatusLine().getReasonPhrase())); } } catch (IOException e) { Log.e("JsonRpcJavaClient", e.getMessage()); e.printStackTrace(); } catch (JSONException e) { Log.e("JsonRpcJavaClient", "Error parsing server JSON response: " + e.getMessage()); e.printStackTrace(); } }
Code Sample 2:
public String useService(HashMap<String, String> input) { String output = ""; if (input.size() < 1) { return ""; } String data = ""; try { for (String key : input.keySet()) { data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(input.get(key), "UTF-8"); } data = data.substring(1); URL url = new URL(serviceUrl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { output += line; } wr.close(); rd.close(); } catch (Exception e) { e.printStackTrace(); } return output; }
|
00
|
Code Sample 1:
void sortclasses() { int i, j; boolean domore; vclassptr = new int[numc]; for (i = 0; i < numc; i++) vclassptr[i] = i; domore = true; while (domore == true) { domore = false; for (i = 0; i < numc - 1; i++) { if (vclassctr[vclassptr[i]] < vclassctr[vclassptr[i + 1]]) { int temp = vclassptr[i]; vclassptr[i] = vclassptr[i + 1]; vclassptr[i + 1] = temp; domore = true; } } } }
Code Sample 2:
public static long toFile(final DigitalObject object, final File file) { try { FileOutputStream fOut = new FileOutputStream(file); long bytesCopied = IOUtils.copyLarge(object.getContent().getInputStream(), fOut); fOut.close(); return bytesCopied; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; }
|
11
|
Code Sample 1:
@Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public void testBlobB() { ResultSet rs; byte[] ba; byte[] baR1 = new byte[] { (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB }; byte[] baR2 = new byte[] { (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB }; try { connection.setAutoCommit(false); Statement st = connection.createStatement(); st.executeUpdate("DROP TABLE blo IF EXISTS"); st.executeUpdate("CREATE TABLE blo (id INTEGER, b blob( 100))"); PreparedStatement ps = connection.prepareStatement("INSERT INTO blo(id, b) values(2, ?)"); ps.setBlob(1, new SerialBlob(baR1)); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } java.sql.Blob blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); byte[] baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); ba = blob1.getBytes(1, baR2.length); if (ba.length != baR2.length) { assertTrue("row2 byte length differs", false); } for (int i = 0; i < ba.length; i++) { if (ba[i] != baR1[i]) { assertTrue("row2 byte " + i + " differs", false); } } rs.close(); connection.rollback(); ps.setBinaryStream(1, new HsqlByteArrayInputStream(baR1), baR1.length); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); fail("test failure"); } }
Code Sample 2:
public void candidatarAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade_has_recurso_humano " + "(atividade_idatividade, usuario_idusuario, ativo) " + "values " + "(" + atividade.getIdAtividade() + ", " + "" + atividade.getRecursoHumano().getIdUsuario() + ", " + "'false')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } }
|
11
|
Code Sample 1:
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
Code Sample 2:
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } }
|
00
|
Code Sample 1:
public void removeExifTag(File jpegImageFile, File dst) throws IOException, ImageReadException, ImageWriteException { OutputStream os = null; try { TiffOutputSet outputSet = null; IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile); JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; if (null != jpegMetadata) { TiffImageMetadata exif = jpegMetadata.getExif(); if (null != exif) { outputSet = exif.getOutputSet(); } } if (null == outputSet) { IOUtils.copyFileNio(jpegImageFile, dst); return; } { outputSet.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); TiffOutputDirectory exifDirectory = outputSet.getExifDirectory(); if (null != exifDirectory) exifDirectory.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); } os = new FileOutputStream(dst); os = new BufferedOutputStream(os); new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet); os.close(); os = null; } finally { if (os != null) try { os.close(); } catch (IOException e) { } } }
Code Sample 2:
public void run() { RandomAccessFile file = null; InputStream stream = null; try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); connection.connect(); if (connection.getResponseCode() / 100 != 2) { error(); } int contentLength = connection.getContentLength(); if (contentLength < 1) { error(); } if (size == -1) { size = contentLength; stateChanged(); } file = new RandomAccessFile(saveas, "rw"); file.seek(downloaded); stream = connection.getInputStream(); while (status == DOWNLOADING) { byte buffer[]; if (size - downloaded > MAX_BUFFER_SIZE) { buffer = new byte[MAX_BUFFER_SIZE]; } else { buffer = new byte[size - downloaded]; } int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); downloaded += read; stateChanged(); } if (status == DOWNLOADING) { status = COMPLETE; stateChanged(); } } catch (Exception e) { e.printStackTrace(); error(); } finally { if (file != null) { try { file.close(); } catch (Exception e) { } } if (stream != null) { try { stream.close(); } catch (Exception e) { } } } }
|
11
|
Code Sample 1:
public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8, 24); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public String computeMD5(String string) throws ServiceException { try { MessageDigest digest = MessageDigest.getInstance("md5"); digest.reset(); digest.update(string.getBytes(Invoker.ENCODING)); return convertToHex(digest.digest()); } catch (NoSuchAlgorithmException exception) { String message = "Could not create properly the MD5 digest"; log.error(message, exception); throw new ServiceException(message, exception); } catch (UnsupportedEncodingException exception) { String message = "Could not encode properly the MD5 digest"; log.error(message, exception); throw new ServiceException(message, exception); } }
|
11
|
Code Sample 1:
public Object mapRow(ResultSet rs, int i) throws SQLException { try { BLOB blob = (BLOB) rs.getBlob(1); OutputStream outputStream = blob.setBinaryStream(0L); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (Exception e) { throw new SQLException(e.getMessage()); } return null; }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void 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(); } } }
|
00
|
Code Sample 1:
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getServerCertificates", args = { }) public final void test_getServerCertificates() throws Exception { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getServerCertificates(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); try { Certificate[] cert = con.getServerCertificates(); fail("SSLPeerUnverifiedException wasn't thrown"); } catch (SSLPeerUnverifiedException e) { } con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); try { Certificate[] cert = con.getServerCertificates(); assertNotNull(cert); assertEquals(1, cert.length); } catch (Exception e) { fail("Unexpected exception " + e); } }
Code Sample 2:
private static int get(URL url, byte[] content) throws IOException { int len = -1; InputStream in = null; try { in = new BufferedInputStream(url.openStream()); String type = URLConnection.guessContentTypeFromStream(in); if (type == null || type.compareTo("text/html") != 0) { return -1; } len = read(in, content); } catch (IOException e) { throw e; } finally { close(in); } return len; }
|
00
|
Code Sample 1:
public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); }
|
11
|
Code Sample 1:
public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.substring(8, 24).toString().toUpperCase(); }
Code Sample 2:
public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
11
|
Code Sample 1:
public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
Code Sample 2:
public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
|
11
|
Code Sample 1:
private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); }
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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void downloadFromUrl(URL url, String localFilename, String userAgent) throws IOException { InputStream is = null; FileOutputStream fos = null; System.setProperty("java.net.useSystemProxies", "true"); try { URLConnection urlConn = url.openConnection(); if (userAgent != null) { urlConn.setRequestProperty("User-Agent", userAgent); } is = urlConn.getInputStream(); fos = new FileOutputStream(localFilename); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } }
Code Sample 2:
public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
|
11
|
Code Sample 1:
public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException { boolean bMatch = false; try { String strSalt = (String) salt; byte[] baSalt = Hex.decodeHex(strSalt.toCharArray()); MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(rawPass.getBytes(CHAR_ENCODING)); md.update(baSalt); byte[] baCalculatedHash = md.digest(); byte[] baStoredHash = Hex.decodeHex(encPass.toCharArray()); bMatch = MessageDigest.isEqual(baCalculatedHash, baStoredHash); } catch (Exception e) { e.printStackTrace(); } return bMatch; }
Code Sample 2:
public static String md5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(value.getBytes()); return bytesToString(messageDigest.digest()); } catch (Exception ex) { Tools.logException(Tools.class, ex, value); } return value; }
|
11
|
Code Sample 1:
public static void main(final String[] args) throws RecognitionException, TokenStreamException, IOException, IllegalOptionValueException, UnknownOptionException { try { CmdLineParser cmdLineParser = new CmdLineParser(); Option formatOption = cmdLineParser.addStringOption('f', "format"); Option encodingOption = cmdLineParser.addStringOption('c', "charset"); cmdLineParser.parse(args); String format = (String) cmdLineParser.getOptionValue(formatOption); String encoding = (String) cmdLineParser.getOptionValue(encodingOption); if (encoding == null || encoding.trim().equals("")) { encoding = "utf-8"; System.out.println("Defaulting to output charset utf-8 as argument -c is missing or not valid."); } String[] remainingArgs = cmdLineParser.getRemainingArgs(); if (remainingArgs.length != 2) { printUsage("Input and output file are not specified correctly. "); } File inputFile = new File(remainingArgs[0]); if (!inputFile.exists()) { printUsage("Input file " + remainingArgs[0] + " does not exist. "); } File outputFile = new File(remainingArgs[1]); if (!outputFile.exists()) { outputFile.createNewFile(); } if (format == null || format.trim().equals("")) { format = (String) FileUtil.cutExtension(outputFile.getName()).getValue(); } if ("tex".equals(format)) { Reader reader = new LatexEncoderReader(new FileReader(inputFile)); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outputFile), encoding); char[] buffer = new char[1024]; int read; do { read = reader.read(buffer); if (read > 0) { out.write(buffer, 0, read); } } while (read != -1); out.flush(); out.close(); } else { printUsage("Format not specified via argument -f. Also guessing for the extension of output file " + outputFile.getName() + " failed"); } } catch (Exception ex) { ex.printStackTrace(); printUsage(ex.getMessage()); } }
Code Sample 2:
private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
|
11
|
Code Sample 1:
public static void main(String[] args) { FTPClient client = new FTPClient(); try { File l_file = new File("C:/temp/testLoribel.html"); String l_url = "http://www.loribel.com/index.html"; GB_HttpTools.loadUrlToFile(l_url, l_file, ENCODING.ISO_8859_1); System.out.println("Try to connect..."); client.connect("ftp://ftp.phpnet.org"); System.out.println("Connected to server"); System.out.println("Try to connect..."); boolean b = client.login("fff", "ddd"); System.out.println("Login: " + b); String[] l_names = client.listNames(); GB_DebugTools.debugArray(GB_FtpDemo2.class, "names", l_names); b = client.makeDirectory("test02/toto"); System.out.println("Mkdir: " + b); String l_remote = "test02/test.xml"; InputStream l_local = new StringInputStream("Test111111111111111"); b = client.storeFile(l_remote, l_local); System.out.println("Copy file: " + b); } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public boolean processFtp(String serverIp, int port, String user, String password, String synchrnPath, String filePath, File[] uploadFile) throws Exception { boolean upload = false; try { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(serverIp)) { throw new RuntimeException("IP is needed. (" + serverIp + ")"); } InetAddress host = InetAddress.getByName(serverIp); ftpClient.connect(host, port); if (!ftpClient.login(user, password)) throw new Exception("FTP Client Login Error : \n"); if (synchrnPath.length() != 0) ftpClient.changeWorkingDirectory(synchrnPath); FTPFile[] fTPFile = ftpClient.listFiles(synchrnPath); FileInputStream fis = null; try { for (int i = 0; i < uploadFile.length; i++) { if (uploadFile[i].isFile()) { if (!isExist(fTPFile, uploadFile[i])) { fis = new FileInputStream(uploadFile[i]); ftpClient.storeFile(synchrnPath + uploadFile[i].getName(), fis); } if (fis != null) { fis.close(); } } } fTPFile = ftpClient.listFiles(synchrnPath); deleteFtpFile(ftpClient, fTPFile, uploadFile); upload = true; } catch (IOException ex) { System.out.println(ex); } finally { if (fis != null) try { fis.close(); } catch (IOException ignore) { System.out.println("IGNORE: " + ignore); } } ftpClient.logout(); } catch (Exception e) { System.out.println(e); upload = false; } return upload; }
|
00
|
Code Sample 1:
public DialogueSymbole(final JFrame jframe, final Element el, final String srcAttr) { super(jframe, JaxeResourceBundle.getRB().getString("symbole.Insertion"), true); this.jframe = jframe; this.el = el; final String nomf = el.getAttribute(srcAttr); boolean applet = false; try { final File dossierSymboles = new File("symboles"); if (!dossierSymboles.exists()) { JOptionPane.showMessageDialog(jframe, JaxeResourceBundle.getRB().getString("erreur.SymbolesNonTrouve"), JaxeResourceBundle.getRB().getString("erreur.Erreur"), JOptionPane.ERROR_MESSAGE); return; } liste = chercherImages(dossierSymboles); } catch (AccessControlException ex) { applet = true; try { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(urlListe.openStream())); final ArrayList<File> listeImages = new ArrayList<File>(); String ligne = null; while ((ligne = in.readLine()) != null) { if (!"".equals(ligne.trim())) listeImages.add(new File("symboles/" + ligne.trim())); } liste = listeImages.toArray(new File[listeImages.size()]); } catch (IOException ex2) { LOG.error(ex2); } } final JPanel cpane = new JPanel(new BorderLayout()); setContentPane(cpane); final GridLayout grille = new GridLayout((int) Math.ceil(liste.length / 13.0), 13, 10, 10); final JPanel spane = new JPanel(grille); cpane.add(spane, BorderLayout.CENTER); ichoix = 0; final MyMouseListener ecouteur = new MyMouseListener(); labels = new JLabel[liste.length]; for (int i = 0; i < liste.length; i++) { if (nomf != null && !"".equals(nomf) && nomf.equals(liste[i].getPath())) ichoix = i; URL urlIcone; try { if (applet) { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); final String baseURL = urlListe.toString().substring(0, urlListe.toString().indexOf("symboles/liste.txt")); urlIcone = new URL(baseURL + liste[i].getPath()); } else urlIcone = liste[i].toURL(); } catch (MalformedURLException ex) { LOG.error(ex); break; } final Icon ic = new ImageIcon(urlIcone); final JLabel label = new JLabel(ic); label.addMouseListener(ecouteur); labels[i] = label; spane.add(label); } final JPanel bpane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); final JButton boutonAnnuler = new JButton(JaxeResourceBundle.getRB().getString("bouton.Annuler")); boutonAnnuler.addActionListener(this); boutonAnnuler.setActionCommand("Annuler"); bpane.add(boutonAnnuler); final JButton boutonOK = new JButton(JaxeResourceBundle.getRB().getString("bouton.OK")); boutonOK.addActionListener(this); boutonOK.setActionCommand("OK"); bpane.add(boutonOK); cpane.add(bpane, BorderLayout.SOUTH); getRootPane().setDefaultButton(boutonOK); choix(ichoix); pack(); if (jframe != null) { final Rectangle r = jframe.getBounds(); setLocation(r.x + r.width / 4, r.y + r.height / 4); } else { final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - getSize().width) / 3, (screen.height - getSize().height) / 3); } }
Code Sample 2:
private PluginInterface getClasseJar(String arquivo) { URLClassLoader load; try { URL url = new URL("jar", "", "file:" + arquivo + "!/"); JarURLConnection jar = (JarURLConnection) url.openConnection(); Enumeration arq = jar.getJarFile().entries(); load = new URLClassLoader(new URL[] { url }); while (arq.hasMoreElements()) { Object object = arq.nextElement(); if (object.toString().contains(".class") && !object.toString().contains("PluginInterface.class")) { Class cl = load.loadClass(object.toString().replace(".class", "")); pl = (PluginInterface) cl.newInstance(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return pl; }
|
00
|
Code Sample 1:
public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; }
Code Sample 2:
public static List<String> extract(String zipFilePath, String destDirPath) throws IOException { List<String> list = null; ZipFile zip = new ZipFile(zipFilePath); try { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destFile = new File(destDirPath, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { InputStream in = zip.getInputStream(entry); OutputStream out = new FileOutputStream(destFile); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { out.close(); } catch (IOException ioe) { ioe.getMessage(); } try { in.close(); } catch (IOException ioe) { ioe.getMessage(); } } } if (list == null) { list = new ArrayList<String>(); } list.add(destFile.getAbsolutePath()); } return list; } finally { try { zip.close(); } catch (Exception e) { e.getMessage(); } } }
|
00
|
Code Sample 1:
public void loadRegistry(URL url) throws PacketAnalyzerRegistryException { if (analyzers != null) { return; } analyzers = new Hashtable(); roots = new Vector(); try { InputStream in = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(in); NodeList list = doc.getElementsByTagName(PACKET_ANALYZER); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); NamedNodeMap map = node.getAttributes(); String id = map.getNamedItem(ID).getNodeValue(); String name = map.getNamedItem(NAME).getNodeValue(); String clazz = map.getNamedItem(CLASS).getNodeValue(); Node n = map.getNamedItem(EXTENDS); String[] split = null; if (n != null) { String extendedAnalyzers = n.getNodeValue(); if (extendedAnalyzers.trim().length() != 0) { split = extendedAnalyzers.split("\\s*\\,+\\s*"); } } PacketAnalyzerDescriptor descriptor = new PacketAnalyzerDescriptor(id, name, clazz, split); addDescriptor(descriptor); } if (roots.size() == 0) { throw new PacketAnalyzerRegistryException("There is no root analyzer in the registry!"); } } catch (IOException e) { throw new PacketAnalyzerRegistryException("Cannot open registry file.", e); } catch (ParserConfigurationException e) { throw new PacketAnalyzerRegistryException("Cannot parse registry file.", e); } catch (SAXException e) { throw new PacketAnalyzerRegistryException("Cannot parse registry file", e); } catch (Throwable e) { throw new PacketAnalyzerRegistryException("Cannot build PacketAnalyzerRegistry.", e); } }
Code Sample 2:
private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } }
|
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 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; }
|
00
|
Code Sample 1:
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(); }
Code Sample 2:
public void deleteGroup(String groupID) throws XregistryException { try { Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_GROUP_SQL_MAIN); statement1.setString(1, groupID); int updateCount = statement1.executeUpdate(); if (updateCount == 0) { throw new XregistryException("Database is not updated, Can not find such Group " + groupID); } if (cascadingDeletes) { PreparedStatement statement2 = connection.prepareStatement(DELETE_GROUP_SQL_DEPEND); statement2.setString(1, groupID); statement2.setString(2, groupID); statement2.executeUpdate(); } connection.commit(); groups.remove(groupID); log.info("Delete Group " + groupID + (cascadingDeletes ? " with cascading deletes " : "")); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public boolean addTextGroup(String key, URL url) { if (_textGroups.contains(key)) return false; String s; Hashtable tg = new Hashtable(); String sGroupKey = "default"; String sGroup[]; Vector vGroup = new Vector(); int cntr; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((s = in.readLine()) != null) { if (s.startsWith("[")) { if (vGroup.size() > 0) { sGroup = new String[vGroup.size()]; for (cntr = 0; cntr < vGroup.size(); ++cntr) sGroup[cntr] = (String) vGroup.elementAt(cntr); tg.put(sGroupKey, sGroup); vGroup.removeAllElements(); } sGroupKey = s.substring(1, s.indexOf(']')); } else { vGroup.addElement(s); } } if (vGroup.size() > 0) { sGroup = new String[vGroup.size()]; for (cntr = 0; cntr < vGroup.size(); ++cntr) sGroup[cntr] = (String) vGroup.elementAt(cntr); tg.put(sGroupKey, sGroup); } in.close(); } catch (IOException ioe) { System.err.println("Error reading file for " + key); System.err.println(ioe.getMessage()); return false; } _textGroups.put(key, tg); return true; }
|
11
|
Code Sample 1:
public static void main(String[] args) { String command = "java -jar "; String linkerJarPath = ""; String path = ""; String osName = System.getProperty("os.name"); String temp = Launcher.class.getResource("").toString(); int index = temp.indexOf(".jar"); int start = index - 1; while (Character.isLetter(temp.charAt(start))) { start--; } String jarName = temp.substring(start + 1, index + 4); System.out.println(jarName); if (osName.startsWith("Linux")) { temp = temp.substring(temp.indexOf("/"), temp.indexOf(jarName)); } else if (osName.startsWith("Windows")) { temp = temp.substring(temp.indexOf("file:") + 5, temp.indexOf(jarName)); } else { System.exit(0); } path = path + temp; try { path = java.net.URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File dir = new File(path); File[] files = dir.listFiles(); String exeJarName = null; for (File f : files) { if (f.getName().endsWith(".jar") && !f.getName().startsWith(jarName)) { exeJarName = f.getName(); break; } } if (exeJarName == null) { System.out.println("no exefile"); System.exit(0); } linkerJarPath = path + exeJarName; String pluginDirPath = path + "plugin" + File.separator; File[] plugins = new File(pluginDirPath).listFiles(); StringBuffer pluginNames = new StringBuffer(""); for (File plugin : plugins) { if (plugin.getAbsolutePath().endsWith(".jar")) { pluginNames.append("plugin/" + plugin.getName() + " "); } } String libDirPath = path + "lib" + File.separator; File[] libs = new File(libDirPath).listFiles(); StringBuffer libNames = new StringBuffer(""); for (File lib : libs) { if (lib.getAbsolutePath().endsWith(".jar")) { libNames.append("lib/" + lib.getName() + " "); } } try { JarFile jarFile = new JarFile(linkerJarPath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { manifest = new Manifest(); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Class-Path", pluginNames.toString() + libNames.toString()); String backupFile = linkerJarPath + "back"; FileInputStream copyInput = new FileInputStream(linkerJarPath); FileOutputStream copyOutput = new FileOutputStream(backupFile); byte[] buffer = new byte[4096]; int s; while ((s = copyInput.read(buffer)) > -1) { copyOutput.write(buffer, 0, s); } copyOutput.flush(); copyOutput.close(); copyInput.close(); JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(linkerJarPath), manifest); JarInputStream jarIn = new JarInputStream(new FileInputStream(backupFile)); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } jarOut.flush(); jarOut.close(); jarIn.close(); File file = new File(backupFile); if (file.exists()) { file.delete(); } } catch (IOException e1) { e1.printStackTrace(); } try { if (System.getProperty("os.name").startsWith("Linux")) { Runtime runtime = Runtime.getRuntime(); String[] commands = new String[] { "java", "-jar", path + exeJarName }; runtime.exec(commands); } else { path = path.substring(1); command = command + "\"" + path + exeJarName + "\""; System.out.println(command); Runtime.getRuntime().exec(command); } } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } }
|
11
|
Code Sample 1:
private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
Code Sample 2:
public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
Code Sample 2:
@Override public void exec() { BufferedReader in = null; try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer result = new StringBuffer(); String str; while ((str = in.readLine()) != null) { result.append(str); } logger.info("received message: " + result); } catch (Exception e) { logger.error("HttpGetEvent could not execute", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
|
11
|
Code Sample 1:
public static boolean copyFileToDir(File inputFile, File outputDir) { try { String outputFileName = inputFile.getName(); int index = 1; while (existFileInDir(outputFileName, outputDir)) { outputFileName = index + inputFile.getName(); index++; } String directory = getDirectoryWithSlash(outputDir.getAbsolutePath()); File outputFile = new File(directory + outputFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { return false; } return true; }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException, IllegalArgumentException { if (src.isDirectory()) throw new IllegalArgumentException("Source file is a directory"); if (dest.isDirectory()) throw new IllegalArgumentException("Destination file is a directory"); int bufferSize = 4 * 1024; InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); }
|
00
|
Code Sample 1:
protected ResourceManager(URL url, String s) { try { properties.load(url.openStream()); path = s; } catch (Exception e) { throw new Error(e.getMessage() + ": trying to load url \"" + url + "\"", e); } }
Code Sample 2:
private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.