label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } }
Code Sample 2:
public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; } |
11
| Code Sample 1:
public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); }
Code Sample 2:
@Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } } |
11
| Code Sample 1:
public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); }
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:
private void copyFile(String path) { try { File srcfile = new File(srcdir, path); File destfile = new File(destdir, path); File parent = destfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); int bytes_read = 0; byte buffer[] = new byte[512]; while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } fis.close(); fos.close(); } catch (IOException e) { throw new BuildException("Error while copying file " + path); } }
Code Sample 2:
@Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); } |
00
| Code Sample 1:
public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } }
Code Sample 2:
private void doLogin() { try { println("Logging in as '" + username.getText() + "'"); URL url = new URL("http://" + hostname + "/migrate"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(URLEncoder.encode("login", "UTF-8") + "=" + encodeCredentials()); wr.flush(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(in); Element root = doc.getDocumentElement(); in.close(); if (root.getAttribute("success").equals("false")) { println("Login Failed: " + getTextContent(root)); JOptionPane.showMessageDialog(this, "Login Failed: " + getTextContent(root), "Login Failed", JOptionPane.ERROR_MESSAGE); } else { token = root.hasAttribute("token") ? root.getAttribute("token") : null; if (token != null) { startImport(); } } } catch (Exception e) { ErrorReporter.showError(e, this); println(e.toString()); } } |
11
| Code Sample 1:
private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
Code Sample 2:
public void end() throws Exception { handle.waitFor(); Calendar endTime = Calendar.getInstance(); File resultsDir = new File(runDir, "results"); if (!resultsDir.isDirectory()) throw new Exception("The results directory not found!"); String resHtml = null; String resTxt = null; String[] resultFiles = resultsDir.list(); for (String resultFile : resultFiles) { if (resultFile.indexOf("html") >= 0) resHtml = resultFile; else if (resultFile.indexOf("txt") >= 0) resTxt = resultFile; } if (resHtml == null) throw new IOException("SPECweb2005 output (html) file not found"); if (resTxt == null) throw new IOException("SPECweb2005 output (txt) file not found"); File resultHtml = new File(resultsDir, resHtml); copyFile(resultHtml.getAbsolutePath(), runDir + "SPECWeb-result.html", false); BufferedReader reader = new BufferedReader(new FileReader(new File(resultsDir, resTxt))); logger.fine("Text file: " + resultsDir + resTxt); Writer writer = new FileWriter(runDir + "summary.xml"); SummaryParser parser = new SummaryParser(getRunId(), startTime, endTime, logger); parser.convert(reader, writer); writer.close(); reader.close(); } |
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 static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } |
00
| Code Sample 1:
@Test public void test00_reinitData() throws Exception { Logs.logMethodName(); init(); Db db = DbConnection.defaultCieDbRW(); try { db.begin(); PreparedStatement pst = db.prepareStatement("TRUNCATE e_module;"); pst.executeUpdate(); pst = db.prepareStatement("TRUNCATE e_application_version;"); pst.executeUpdate(); ModuleHelper.synchronizeDbWithModuleList(db); ModuleHelper.declareNewVersion(db); ModuleHelper.updateModuleVersions(db); esisId = com.entelience.directory.PeopleFactory.lookupUserName(db, "esis"); assertNotNull(esisId); guestId = com.entelience.directory.PeopleFactory.lookupUserName(db, "guest"); assertNotNull(guestId); extenId = com.entelience.directory.PeopleFactory.lookupUserName(db, "exten"); assertNotNull(extenId); db.commit(); } catch (Exception e) { db.rollback(); throw e; } }
Code Sample 2:
public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; } |
11
| Code Sample 1:
protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); }
Code Sample 2:
private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); } |
11
| Code Sample 1:
public static String getWebPage(URL urlObj) { try { String content = ""; InputStreamReader is = new InputStreamReader(urlObj.openStream()); BufferedReader reader = new BufferedReader(is); String line; while ((line = reader.readLine()) != null) { content += line; } return content; } catch (IOException e) { throw new Error("The page " + quote(urlObj.toString()) + "could not be retrieved." + "\nThis is could be caused by a number of things:" + "\n" + "\n - the computer hosting the web page you want is down, or has returned an error" + "\n - your computer does not have Internet access" + "\n - the heat death of the universe has occurred, taking down all web servers with it"); } }
Code Sample 2:
public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } } |
00
| Code Sample 1:
protected void download() { boolean connected = false; String outcome = ""; try { InputStream is = null; try { SESecurityManager.setThreadPasswordHandler(this); synchronized (this) { if (destroyed) { return; } scratch_file = AETemporaryFileHandler.createTempFile(); raf = new RandomAccessFile(scratch_file, "rw"); } HttpURLConnection connection; int response; connection = (HttpURLConnection) original_url.openConnection(); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", user_agent); int time_remaining = listener.getPermittedTime(); if (time_remaining > 0) { Java15Utils.setConnectTimeout(connection, time_remaining); } connection.connect(); time_remaining = listener.getPermittedTime(); if (time_remaining < 0) { throw (new IOException("Timeout during connect")); } Java15Utils.setReadTimeout(connection, time_remaining); connected = true; response = connection.getResponseCode(); last_response = response; last_response_retry_after_secs = -1; if (response == 503) { long retry_after_date = new Long(connection.getHeaderFieldDate("Retry-After", -1L)).longValue(); if (retry_after_date <= -1) { last_response_retry_after_secs = connection.getHeaderFieldInt("Retry-After", -1); } else { last_response_retry_after_secs = (int) ((retry_after_date - System.currentTimeMillis()) / 1000); if (last_response_retry_after_secs < 0) { last_response_retry_after_secs = -1; } } } is = connection.getInputStream(); if (response == HttpURLConnection.HTTP_ACCEPTED || response == HttpURLConnection.HTTP_OK || response == HttpURLConnection.HTTP_PARTIAL) { byte[] buffer = new byte[64 * 1024]; int requests_outstanding = 1; while (!destroyed) { int permitted = listener.getPermittedBytes(); if (requests_outstanding == 0 || permitted < 1) { permitted = 1; Thread.sleep(100); } int len = is.read(buffer, 0, Math.min(permitted, buffer.length)); if (len <= 0) { break; } synchronized (this) { try { raf.write(buffer, 0, len); } catch (Throwable e) { outcome = "Write failed: " + e.getMessage(); ExternalSeedException error = new ExternalSeedException(outcome, e); error.setPermanentFailure(true); throw (error); } } listener.reportBytesRead(len); requests_outstanding = checkRequests(); } checkRequests(); } else { outcome = "Connection failed: " + connection.getResponseMessage(); ExternalSeedException error = new ExternalSeedException(outcome); error.setPermanentFailure(true); throw (error); } } catch (IOException e) { if (con_fail_is_perm_fail && !connected) { outcome = "Connection failed: " + e.getMessage(); ExternalSeedException error = new ExternalSeedException(outcome); error.setPermanentFailure(true); throw (error); } else { outcome = "Connection failed: " + Debug.getNestedExceptionMessage(e); if (last_response_retry_after_secs >= 0) { outcome += ", Retry-After: " + last_response_retry_after_secs + " seconds"; } ExternalSeedException excep = new ExternalSeedException(outcome, e); if (e instanceof FileNotFoundException) { excep.setPermanentFailure(true); } throw (excep); } } catch (ExternalSeedException e) { throw (e); } catch (Throwable e) { if (e instanceof ExternalSeedException) { throw ((ExternalSeedException) e); } outcome = "Connection failed: " + Debug.getNestedExceptionMessage(e); throw (new ExternalSeedException("Connection failed", e)); } finally { SESecurityManager.unsetThreadPasswordHandler(); if (is != null) { try { is.close(); } catch (Throwable e) { } } } } catch (ExternalSeedException e) { if (!connected && con_fail_is_perm_fail) { e.setPermanentFailure(true); } destroy(e); } }
Code Sample 2:
private static BundleInfo[] getBundleInfoArray(String location) throws IOException { URL url = new URL(location + BUNDLE_LIST_FILE); BufferedReader br = null; List<BundleInfo> list = new ArrayList<BundleInfo>(); try { br = new BufferedReader(new InputStreamReader(url.openStream())); while (true) { String line = br.readLine(); if (line == null) { break; } int pos1 = line.indexOf('='); if (pos1 < 0) { continue; } BundleInfo info = new BundleInfo(); info.bundleSymbolicName = line.substring(0, pos1); info.location = line.substring(pos1 + 1); list.add(info); } if (!setBundleInfoName(location + BUNDLE_NAME_LIST_FILE + "_" + Locale.getDefault().getLanguage(), list)) { setBundleInfoName(location + BUNDLE_NAME_LIST_FILE, list); } return list.toArray(BUNDLE_INFO_EMPTY_ARRAY); } finally { if (br != null) { br.close(); } } } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static 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(); } } } } |
00
| Code Sample 1:
private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); }
Code Sample 2:
@Test public void testStandardTee() throws Exception { final byte[] test = "test".getBytes(); final InputStream source = new ByteArrayInputStream(test); final ByteArrayOutputStream destination1 = new ByteArrayOutputStream(); final ByteArrayOutputStream destination2 = new ByteArrayOutputStream(); final TeeOutputStream tee = new TeeOutputStream(destination1, destination2); org.apache.commons.io.IOUtils.copy(source, tee); tee.close(); assertArrayEquals("the two arrays are equals", test, destination1.toByteArray()); assertArrayEquals("the two arrays are equals", test, destination2.toByteArray()); assertEquals("byte count", test.length, tee.getSize()); } |
00
| Code Sample 1:
protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method); request.setDoOutput(true); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream())); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } }
Code Sample 2:
@Test public void shouldDownloadFileUsingPublicLink() throws Exception { String bucketName = "test-" + UUID.randomUUID(); Service service = new WebClientService(credentials); service.createBucket(bucketName); File file = folder.newFile("foo.txt"); FileUtils.writeStringToFile(file, UUID.randomUUID().toString()); service.createObject(bucketName, file.getName(), file, new NullProgressListener()); String publicUrl = service.getPublicUrl(bucketName, file.getName(), new DateTime().plusDays(5)); File saved = folder.newFile("saved.txt"); InputStream input = new URL(publicUrl).openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(saved); IOUtils.copy(input, output); output.close(); assertThat("Corrupted download", Files.computeMD5(saved), equalTo(Files.computeMD5(file))); service.deleteObject(bucketName, file.getName()); service.deleteBucket(bucketName); } |
11
| Code Sample 1:
public static boolean copyFile(File sourceFile, File destFile) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(sourceFile).getChannel(); dstChannel = new FileOutputStream(destFile).getChannel(); long pos = 0; long count = srcChannel.size(); if (count > MAX_BLOCK_SIZE) { count = MAX_BLOCK_SIZE; } long transferred = Long.MAX_VALUE; while (transferred > 0) { transferred = dstChannel.transferFrom(srcChannel, pos, count); pos = transferred; } } catch (IOException e) { return false; } finally { if (srcChannel != null) { try { srcChannel.close(); } catch (IOException e) { } } if (dstChannel != null) { try { dstChannel.close(); } catch (IOException e) { } } } return true; }
Code Sample 2:
protected InputStream createIconType(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { JavaliController.debug(JavaliController.LG_VERBOSE, "Creating iconType"); String cHash = PRM_TYPE + "=" + TP_ICON; String iconName = req.getParameter("iconName"); if (iconName == null) { res.sendError(res.SC_NOT_FOUND); return null; } Locale loc = null; HttpSession sess = req.getSession(false); JavaliSession jsess = null; int menuType = -1; String menuTypeString = req.getParameter(PRM_MENU_TYPE); try { menuType = new Integer(menuTypeString).intValue(); } catch (Exception e) { } if (sess != null) jsess = (JavaliSession) sess.getAttribute(FormConstants.SESSION_BINDING); if (jsess != null && jsess.getUser() != null) loc = jsess.getUser().getLocale(); else if (sess != null) loc = (Locale) sess.getAttribute(FormConstants.LOCALE_BINDING); if (loc == null) loc = Locale.getDefault(); if (menuType == -1) menuType = MENU_TYPE_TEXTICON; String iconText = JavaliResource.getString("icon." + iconName, loc); if (iconText == null) { iconText = req.getParameter(PRM_MENU_NAME); if (iconText == null) iconText = ""; } cHash += ", " + PRM_ICON_NAME + "=" + iconName + ", text=" + iconText + ", menuType=" + menuType; String iconFileName = null; String fontName = req.getParameter(PRM_FONT_NAME); if (fontName == null) { fontName = "Helvetica"; } cHash += "," + PRM_FONT_NAME + "=" + fontName; String fontSizeString = req.getParameter(PRM_FONT_SIZE); int fontSize; try { fontSize = Integer.parseInt(fontSizeString); } catch (NumberFormatException nfe) { fontSize = 12; } cHash += "," + PRM_FONT_SIZE + "=" + fontSize; String fontTypeString = req.getParameter(PRM_FONT_TYPE); int fontType = Font.BOLD; if ("PLAIN".equalsIgnoreCase(fontTypeString)) fontType = Font.PLAIN; if ("BOLD".equalsIgnoreCase(fontTypeString)) fontType = Font.BOLD; if ("ITALIC".equalsIgnoreCase(fontTypeString)) fontType = Font.ITALIC; if ("ITALICBOLD".equalsIgnoreCase(fontTypeString) || "BOLDITALIC".equalsIgnoreCase(fontTypeString) || "BOLD_ITALIC".equalsIgnoreCase(fontTypeString) || "ITALIC_BOLD".equalsIgnoreCase(fontTypeString)) { fontType = Font.ITALIC | Font.BOLD; } cHash += "," + PRM_FONT_TYPE + "=" + fontType; String fontColor = req.getParameter(PRM_FONT_COLOR); if (fontColor == null || fontColor.equals("")) fontColor = "0x000000"; cHash += "," + PRM_FONT_COLOR + "=" + fontColor; String fName = cacheInfo.file(cHash); JavaliController.debug(JavaliController.LG_VERBOSE, "Called for: " + fName); if (fName == null) { JavaliController.debug(JavaliController.LG_VERBOSE, "No cache found for: " + cHash); if (getServletConfig() != null && getServletConfig().getServletContext() != null) { if (iconName != null && iconName.startsWith("/")) iconFileName = getServletConfig().getServletContext().getRealPath(iconName + ".gif"); else iconFileName = getServletConfig().getServletContext().getRealPath("/icons/" + iconName + ".gif"); File iconFile = new File(iconFileName); if (!iconFile.exists()) { JavaliController.debug(JavaliController.LG_VERBOSE, "Could not find: " + iconFileName); res.sendError(res.SC_NOT_FOUND); return null; } iconFileName = iconFile.getAbsolutePath(); JavaliController.debug(JavaliController.LG_VERBOSE, "file: " + iconFileName + " and cHash=" + cHash); } else { JavaliController.debug(JavaliController.LG_VERBOSE, "No ServletConfig=" + getServletConfig() + " or servletContext"); res.sendError(res.SC_NOT_FOUND); return null; } File tmp = File.createTempFile(PREFIX, SUFIX, cacheDir); OutputStream out = new FileOutputStream(tmp); if (menuType == MENU_TYPE_ICON) { FileInputStream in = new FileInputStream(iconFileName); byte buf[] = new byte[2048]; int read = -1; while ((read = in.read(buf)) != -1) out.write(buf, 0, read); } else if (menuType == MENU_TYPE_TEXT) MessageImage.sendAsGIF(MessageImage.makeMessageImage(iconText, fontName, fontSize, fontType, fontColor, false, "0x000000", true), out); else MessageImage.sendAsGIF(MessageImage.makeIconImage(iconFileName, iconText, fontName, fontColor, fontSize, fontType), out); out.close(); cacheInfo.putFile(cHash, tmp); fName = cacheInfo.file(cHash); } return new FileInputStream(new File(cacheDir, fName)); } |
11
| Code Sample 1:
public static void main(String[] args) throws MalformedURLException, IOException { InputStream in = null; try { in = new URL("hdfs://localhost:8020/user/leeing/maxtemp/sample.txt").openStream(); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); System.out.println("\nend."); } }
Code Sample 2:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } |
00
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static final synchronized String md5(final String data) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data.getBytes()); final byte[] b = md.digest(); return toHexString(b); } catch (final Exception e) { } return ""; } |
00
| Code Sample 1:
@Override public boolean putDescription(String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { PreparedStatement findSt = getConnection().prepareStatement(SELECT_COMMON_DESCRIPTION_STATEMENT); PreparedStatement updSt = null; findSt.setString(1, uuid); ResultSet rs = findSt.executeQuery(); found = rs.next(); int modified = 0; updSt = getConnection().prepareStatement(found ? UPDATE_COMMON_DESCRIPTION_STATEMENT : INSERT_COMMON_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + findSt + "\" and \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + findSt + "\" and \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; }
Code Sample 2:
public void mkdirs(String path) throws IOException { GridFTP ftp = new GridFTP(); ftp.setDefaultPort(port); System.out.println(this + ".mkdirs " + path); try { ftp.connect(host); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection."); } ftp.mkdirs(path); ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } |
00
| Code Sample 1:
@SuppressWarnings("static-access") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { filename = URLDecoder.decode(filename, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { is = request.getInputStream(); File newFile = new File(realPath + filename); if (!newFile.exists()) { fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true,detailMsg}"); } else { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false,detailMsg:'文件已经存在!请重命名后上传!'}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!"); } } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
private void alterarArtista(Artista artista) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE artista SET nome = ?,sexo = ?,email = ?,obs = ?,telefone = ? where numeroinscricao = ?"; ps = conn.prepareStatement(sql); ps.setString(1, artista.getNome()); ps.setBoolean(2, artista.isSexo()); ps.setString(3, artista.getEmail()); ps.setString(4, artista.getObs()); ps.setString(5, artista.getTelefone()); ps.setInt(6, artista.getNumeroInscricao()); ps.executeUpdate(); alterarEndereco(conn, ps, artista); delObras(conn, ps, artista.getNumeroInscricao()); sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); for (Obra obra : artista.getListaObras()) { salvarObra(conn, ps, obra, artista.getNumeroInscricao()); } conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } |
11
| Code Sample 1:
public void doNew(Vector userId, String shareFlag, String folderId) throws AddrException { DBOperation dbo = null; Connection connection = null; PreparedStatement ps = null; ResultSet rset = null; String sql = "insert into " + SHARE_TABLE + " values(?,?,?)"; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); for (int i = 0; i < userId.size(); i++) { String user = (String) userId.elementAt(i); ps = connection.prepareStatement(sql); ps.setInt(1, Integer.parseInt(folderId)); ps.setInt(2, Integer.parseInt(user)); ps.setString(3, shareFlag); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new Exception("error"); } } connection.commit(); } catch (Exception ex) { if (connection != null) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } logger.error("���������ļ�����Ϣʧ��, " + ex.getMessage()); throw new AddrException("���������ļ�����Ϣʧ��,һ�������ļ���ֻ�ܹ����ͬһ�û�һ��!"); } finally { close(rset, null, ps, connection, dbo); } }
Code Sample 2:
public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_CURRENCY")); pst.setString(1, curr.getName()); pst.setInt(2, curr.getIdBase()); pst.setDouble(3, curr.getValue()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from currency"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; } |
00
| Code Sample 1:
private void packageDestZip(File tmpFile) throws FileNotFoundException, IOException { log("Creating launch profile package " + destfile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destfile))); ZipEntry e = new ZipEntry(RESOURCE_JAR_FILENAME); e.setMethod(ZipEntry.STORED); e.setSize(tmpFile.length()); e.setCompressedSize(tmpFile.length()); e.setCrc(calcChecksum(tmpFile, new CRC32())); out.putNextEntry(e); InputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.closeEntry(); out.finish(); out.close(); }
Code Sample 2:
public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } |
00
| Code Sample 1:
private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); }
Code Sample 2:
public String getMethod(String url) { logger.info("Facebook: @executing facebookGetMethod():" + url); String responseStr = null; try { HttpGet loginGet = new HttpGet(url); loginGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = httpClient.execute(loginGet); HttpEntity entity = response.getEntity(); logger.trace("Facebook: facebookGetMethod: " + response.getStatusLine()); if (entity != null) { InputStream in = response.getEntity().getContent(); if (response.getEntity().getContentEncoding().getValue().equals("gzip")) { in = new GZIPInputStream(in); } StringBuffer sb = new StringBuffer(); byte[] b = new byte[4096]; int n; while ((n = in.read(b)) != -1) { sb.append(new String(b, 0, n)); } responseStr = sb.toString(); in.close(); entity.consumeContent(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { logger.warn("Facebook: Error Occured! Status Code = " + statusCode); responseStr = null; } logger.info("Facebook: Get Method done(" + statusCode + "), response string length: " + (responseStr == null ? 0 : responseStr.length())); } catch (IOException e) { logger.warn("Facebook: ", e); } return responseStr; } |
11
| Code Sample 1:
protected void extractArchive(File archive) { ZipInputStream zis = null; FileOutputStream fos; ZipEntry entry; File curEntry; int n; try { zis = new ZipInputStream(new FileInputStream(archive)); while ((entry = zis.getNextEntry()) != null) { curEntry = new File(workingDir, entry.getName()); if (entry.isDirectory()) { System.out.println("skip directory: " + entry.getName()); continue; } System.out.print("zip-entry (file): " + entry.getName()); System.out.println(" ==> real path: " + curEntry.getAbsolutePath()); if (!curEntry.getParentFile().exists()) curEntry.getParentFile().mkdirs(); fos = new FileOutputStream(curEntry); while ((n = zis.read(buf, 0, buf.length)) > -1) fos.write(buf, 0, n); fos.close(); zis.closeEntry(); } } catch (Throwable t) { t.printStackTrace(); } finally { try { if (zis != null) zis.close(); } catch (Throwable t) { } } }
Code Sample 2:
@Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); } |
00
| Code Sample 1:
private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; }
Code Sample 2:
public int extract() throws Exception { int count = 0; if (VERBOSE) System.out.println("IAAE:Extractr.extract: getting ready to extract " + getArtDir().toString()); ITCFileFilter iff = new ITCFileFilter(); RecursiveFileIterator rfi = new RecursiveFileIterator(getArtDir(), iff); FileTypeDeterminer ftd = new FileTypeDeterminer(); File artFile = null; File targetFile = null; broadcastStart(); while (rfi.hasMoreElements()) { artFile = (File) rfi.nextElement(); targetFile = getTargetFile(artFile); if (VERBOSE) System.out.println("IAAE:Extractr.extract: working ont " + artFile.toString()); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream((new FileInputStream(artFile))); out = new BufferedOutputStream((new FileOutputStream(targetFile))); byte[] buffer = new byte[10240]; int read = 0; int total = 0; read = in.read(buffer); while (read != -1) { if ((total <= 491) && (read > 491)) { out.write(buffer, 492, (read - 492)); } else if ((total <= 491) && (read <= 491)) { } else { out.write(buffer, 0, read); } total = total + read; read = in.read(buffer); } } catch (Exception e) { e.printStackTrace(); broadcastFail(); } finally { in.close(); out.close(); } broadcastSuccess(); count++; } broadcastDone(); return count; } |
11
| Code Sample 1:
public String getHashedPhoneId(Context aContext) { if (hashedPhoneId == null) { final String androidId = BuildInfo.getAndroidID(aContext); if (androidId == null) { hashedPhoneId = "EMULATOR"; } else { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(androidId.getBytes()); messageDigest.update(aContext.getPackageName().getBytes()); final StringBuilder stringBuilder = new StringBuilder(); for (byte b : messageDigest.digest()) { stringBuilder.append(String.format("%02X", b)); } hashedPhoneId = stringBuilder.toString(); } catch (Exception e) { Log.e(LoggingExceptionHandler.class.getName(), "Unable to get phone id", e); hashedPhoneId = "Not Available"; } } } return hashedPhoneId; }
Code Sample 2:
public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; } |
00
| Code Sample 1:
String digest(final UserAccountEntity account) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(account.getUserId().getBytes("UTF-8")); digest.update(account.getLastLogin().toString().getBytes("UTF-8")); digest.update(account.getPerson().getGivenName().getBytes("UTF-8")); digest.update(account.getPerson().getSurname().getBytes("UTF-8")); digest.update(account.getPerson().getEmail().getBytes("UTF-8")); digest.update(m_random); return new String(Base64.altEncode(digest.digest())); } catch (final Exception e) { LOG.error("Exception", e); throw new RuntimeException(e); } }
Code Sample 2:
public void copy(File source, File dest) throws IOException { System.out.println("copy " + source + " -> " + dest); FileInputStream in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { out.close(); } } finally { in.close(); } } |
00
| Code Sample 1:
public void play() throws FileNotFoundException, IOException, NoSuchAlgorithmException, FTPException { final int BUFFER = 2048; String host = "ftp.genome.jp"; String username = "anonymous"; String password = ""; FTPClient ftp = null; ftp = new FTPClient(); ftp.setRemoteHost(host); FTPMessageCollector listener = new FTPMessageCollector(); ftp.setMessageListener(listener); System.out.println("Connecting"); ftp.connect(); System.out.println("Logging in"); ftp.login(username, password); System.out.println("Setting up passive, ASCII transfers"); ftp.setConnectMode(FTPConnectMode.PASV); ftp.setType(FTPTransferType.ASCII); System.out.println("Directory before put:"); String[] files = ftp.dir(".", true); for (int i = 0; i < files.length; i++) System.out.println(files[i]); System.out.println("Quitting client"); ftp.quit(); String messages = listener.getLog(); System.out.println("Listener log:"); System.out.println(messages); System.out.println("Test complete"); }
Code Sample 2:
private void logoutUser(String session) { try { String data = URLEncoder.encode("SESSION", "UTF-8") + "=" + URLEncoder.encode("" + session, "UTF-8"); if (_log != null) _log.error("Voice: logoutUser = " + m_strUrl + "LogoutUserServlet&" + data); URL url = new URL(m_strUrl + "LogoutUserServlet"); 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())); wr.close(); rd.close(); } catch (Exception e) { if (_log != null) _log.error("Voice error : " + e); } } |
00
| Code Sample 1:
private void copyFile(File src_file, File dest_file) { InputStream src_stream = null; OutputStream dest_stream = null; try { int b; src_stream = new BufferedInputStream(new FileInputStream(src_file)); dest_stream = new BufferedOutputStream(new FileOutputStream(dest_file)); while ((b = src_stream.read()) != -1) dest_stream.write(b); } catch (Exception e) { XRepository.getLogger().warning(this, "Error on copying the plugin file!"); XRepository.getLogger().warning(this, e); } finally { try { src_stream.close(); dest_stream.close(); } catch (Exception ex2) { } } }
Code Sample 2:
protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient f = new FTPClient(); f.connect(fpi.getHost()); f.login(fpi.getUsername(), fpi.getPassword()); return f; } |
11
| Code Sample 1:
public String hash(String plainTextPassword) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(plainTextPassword.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(org.jboss.seam.util.Hex.encodeHex(rawHash)); } catch (NoSuchAlgorithmException e) { log.error("Digest algorithm #0 to calculate the password hash will not be supported.", digestAlgorithm); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { log.error("The Character Encoding #0 is not supported", charset); throw new RuntimeException(e); } }
Code Sample 2:
private String md5Digest(String plain) throws Exception { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(plain.trim().getBytes()); byte pwdDigest[] = digest.digest(); StringBuilder md5buffer = new StringBuilder(); for (int i = 0; i < pwdDigest.length; i++) { int number = 0xFF & pwdDigest[i]; if (number <= 0xF) { md5buffer.append('0'); } md5buffer.append(Integer.toHexString(number)); } return md5buffer.toString(); } |
00
| Code Sample 1:
public boolean loadResource(String resourcePath) { try { URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (url == null) { logger.error("Cannot find the resource named: '" + resourcePath + "'. Failed to load the keyword list."); return false; } InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ligne = br.readLine(); while (ligne != null) { if (!contains(ligne.toUpperCase())) { addLast(ligne.toUpperCase()); } ligne = br.readLine(); } return true; } catch (IOException ioe) { logger.log(Level.ERROR, "Cannot load default SQL keywords file.", ioe); } return false; }
Code Sample 2:
private int create() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; String query = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); query = "insert into " + DB.Tbl.users + "(" + col.name + "," + col.login + "," + col.pass + "," + col.passHash + "," + col.email + "," + col.role + "," + col.addDate + ") values('" + name + "','" + login + "','" + pass + "','" + pass.hashCode() + "','" + email + "'," + role + ",now())"; st.executeUpdate(query, new String[] { col.id }); rs = st.getGeneratedKeys(); while (rs.next()) { int genId = rs.getInt(1); conn.commit(); return genId; } throw new SQLException("Не удается получить generatedKey при создании пользователя."); } catch (SQLException e) { try { conn.rollback(); } catch (Exception e1) { } throw e; } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } } |
11
| Code Sample 1:
private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public void run() { FileInputStream src; FileOutputStream dest; try { dest = new FileOutputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel destC = dest.getChannel(); FileChannel srcC; ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int fileNo = 0; while (true) { int i = 1; String destName = srcName + "_" + fileNo; src = new FileInputStream(destName); srcC = src.getChannel(); while ((i > 0)) { i = srcC.read(buf); buf.flip(); destC.write(buf); buf.compact(); } srcC.close(); src.close(); fileNo++; } } catch (IOException e1) { e1.printStackTrace(); return; } } |
00
| Code Sample 1:
@Override public boolean validatePublisher(Object object, String... dbSettingParams) { DBConnectionListener listener = (DBConnectionListener) object; String host = dbSettingParams[0]; String port = dbSettingParams[1]; String driver = dbSettingParams[2]; String type = dbSettingParams[3]; String dbHost = dbSettingParams[4]; String dbName = dbSettingParams[5]; String dbUser = dbSettingParams[6]; String dbPassword = dbSettingParams[7]; boolean validPublisher = false; String url = "http://" + host + ":" + port + "/reports"; try { URL _url = new URL(url); _url.openConnection().connect(); validPublisher = true; } catch (Exception e) { log.log(Level.FINE, "Failed validating url " + url, e); } if (validPublisher) { Connection conn; try { if (driver != null) { conn = DBProperties.getInstance().getConnection(driver, dbHost, dbName, type, dbUser, dbPassword); } else { conn = DBProperties.getInstance().getConnection(); } } catch (Exception e) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } if (validPublisher) { if (!allNecessaryTablesCreated(conn)) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } listener.connectionIsOk(true, conn); } } else { listener.connectionIsOk(false, null); } return validPublisher; }
Code Sample 2:
public static void decompress(File apps,File f) throws IOException{ String filename=f.getName(); filename=filename.substring(0,filename.length()-PACK_FILE_SUFFIX.length()); File dir=new File(apps,filename); if(!dir.exists()){ dir.mkdirs(); } if(dir.isDirectory()){ JarFile jar=new JarFile(f); Enumeration<JarEntry> files=jar.entries(); while(files.hasMoreElements()){ JarEntry je=files.nextElement(); if(je.isDirectory()){ File item=new File(dir,je.getName()); item.mkdirs(); }else{ File item=new File(dir,je.getName()); item.getParentFile().mkdirs(); InputStream input=jar.getInputStream(je); FileOutputStream out=new FileOutputStream(item); IOUtils.copy(input, out); input.close(); out.close(); } //System.out.println(je.isDirectory() + je.getName()); } } } |
00
| Code Sample 1:
public static void fileTrans(String filePath, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } File file = new File(filePath); try { FileInputStream fis = new FileInputStream(file); Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream)); byte[] buffer = new byte[2048]; int num = fis.read(buffer); while (num != -1) { dataOutputStream.write(buffer, 0, num); dataOutputStream.flush(); num = fis.read(buffer); } fis.close(); dataOutputStream.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void gzip(File from, File to) { OutputStream out_zip = null; ArchiveOutputStream os = null; try { try { out_zip = new FileOutputStream(to); os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out_zip); os.putArchiveEntry(new ZipArchiveEntry(from.getName())); IOUtils.copy(new FileInputStream(from), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out_zip.close(); } catch (IOException ex) { fatal("IOException", ex); } catch (ArchiveException ex) { fatal("ArchiveException", ex); } } |
00
| Code Sample 1:
void readFileHeader(DmgConfigDMO config, ConfigLocation sl) throws IOException { fileHeader = ""; if (config.getGeneratedFileHeader() != null) { StringBuffer sb = new StringBuffer(); if (sl.getJarFilename() != null) { URL url = new URL("jar:file:" + sl.getJarFilename() + "!/" + sl.getJarDirectory() + "/" + config.getGeneratedFileHeader()); LineNumberReader in = new LineNumberReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { sb.append(str + "\n"); } in.close(); } else { LineNumberReader in = new LineNumberReader(new FileReader(sl.getDirectory() + File.separator + config.getGeneratedFileHeader())); String str; while ((str = in.readLine()) != null) { sb.append(str + "\n"); } in.close(); } fileHeader = sb.toString(); } }
Code Sample 2:
public void run() { StringBuffer messageStringBuffer = new StringBuffer(); messageStringBuffer.append("Program: \t" + UpdateChannel.getCurrentChannel().getApplicationTitle() + "\n"); messageStringBuffer.append("Version: \t" + Lister.version + "\n"); messageStringBuffer.append("Revision: \t" + Lister.revision + "\n"); messageStringBuffer.append("Channel: \t" + UpdateChannel.getCurrentChannel().getName() + "\n"); messageStringBuffer.append("Date: \t\t" + Lister.date + "\n\n"); messageStringBuffer.append("OS: \t\t" + System.getProperty("os.name") + " (" + System.getProperty("os.version") + ")\n"); messageStringBuffer.append("JAVA: \t\t" + System.getProperty("java.version") + " (" + System.getProperty("java.specification.vendor") + ")\n"); messageStringBuffer.append("Desktop: \t" + System.getProperty("sun.desktop") + "\n"); messageStringBuffer.append("Language: \t" + Language.getCurrentInstance() + "\n\n"); messageStringBuffer.append("------------------------------------------\n"); if (summary != null) { messageStringBuffer.append(summary + "\n\n"); } messageStringBuffer.append("Details:\n"); if (description != null) { messageStringBuffer.append(description); } if (exception != null) { messageStringBuffer.append("\n\nStacktrace:\n"); printStackTrace(exception, messageStringBuffer); } try { if (dialog != null) { setComponentsEnabled(dialog.getContentPane(), false); } URL url = UpdateChannel.getCurrentChannel().getErrorReportURL(); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); if (sender != null) { outputStreamWriter.write(URLEncoder.encode("sender", "UTF-8") + "=" + URLEncoder.encode(sender, "UTF-8")); outputStreamWriter.write("&"); } outputStreamWriter.write(URLEncoder.encode("report", "UTF-8") + "=" + URLEncoder.encode(messageStringBuffer.toString(), "UTF-8")); if (attachErrorLog) { outputStreamWriter.write("&"); outputStreamWriter.write(URLEncoder.encode("error.log", "UTF-8") + "=" + URLEncoder.encode(Logger.getErrorLogContent(), "UTF-8")); } outputStreamWriter.flush(); urlConnection.getInputStream().close(); outputStreamWriter.close(); if (dialog != null) { dialog.dispose(); } JOptionPane.showMessageDialog(Lister.getCurrentInstance(), Language.translateStatic("MESSAGE_ERRORREPORTSENT")); } catch (Exception exception) { ErrorJDialog.showErrorDialog(dialog, exception); if (dialog != null) { setComponentsEnabled(dialog.getContentPane(), true); } } } |
00
| Code Sample 1:
protected UnicodeList(URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); String line; line = br.readLine(); chars = new ArrayList(); while ((line = br.readLine()) != null) { String[] parts = GUIHelper.split(line, ";"); if (parts[0].length() >= 5) continue; if (parts.length < 2 || parts[0].length() != 4) { System.out.println("Strange line: " + line); } else { if (parts.length > 10 && parts[1].equals("<control>")) { parts[1] = parts[1] + ": " + parts[10]; } try { Integer.parseInt(parts[0], 16); chars.add(parts[0] + parts[1]); } catch (NumberFormatException ex) { System.out.println("No number: " + line); } } } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
protected void configureGraphicalViewer() { super.configureGraphicalViewer(); GraphicalViewer viewer = getGraphicalViewer(); viewer.setEditPartFactory(createEditPartFactory()); ScalableRootEditPart rootEditPart = new ScalableRootEditPart(); viewer.setRootEditPart(rootEditPart); ZoomManager manager = rootEditPart.getZoomManager(); double[] zoomLevels = new double[] { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 20.0 }; manager.setZoomLevels(zoomLevels); ArrayList zoomContributions = new ArrayList(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); manager.setZoomLevelContributions(zoomContributions); getActionRegistry().registerAction(new ZoomInAction(manager)); getActionRegistry().registerAction(new ZoomOutAction(manager)); getGraphicalViewer().setKeyHandler(new GraphicalViewerKeyHandler(getGraphicalViewer())); String menuId = this.getClass().getName() + ".EditorContext"; MenuManager menuMgr = new MenuManager(menuId, menuId); openPropertyAction = new OpenPropertyViewAction(viewer); openOutlineAction = new OpenOutlineViewAction(viewer); saveAsImageAction = new SaveAsImageAction(viewer); createDiagramAction(viewer); getSite().registerContextMenu(menuId, menuMgr, viewer); PrintAction printAction = new PrintAction(this); printAction.setImageDescriptor(UMLPlugin.getImageDescriptor("icons/print.gif")); getActionRegistry().registerAction(printAction); final DeleteAction deleteAction = new DeleteAction((IWorkbenchPart) this); deleteAction.setSelectionProvider(getGraphicalViewer()); getActionRegistry().registerAction(deleteAction); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { deleteAction.update(); } }); menuMgr.add(new Separator("edit")); menuMgr.add(getActionRegistry().getAction(ActionFactory.DELETE.getId())); menuMgr.add(getActionRegistry().getAction(ActionFactory.UNDO.getId())); menuMgr.add(getActionRegistry().getAction(ActionFactory.REDO.getId())); menuMgr.add(new Separator("zoom")); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_IN)); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_OUT)); fillDiagramPopupMenu(menuMgr); menuMgr.add(new Separator("print")); menuMgr.add(saveAsImageAction); menuMgr.add(printAction); menuMgr.add(new Separator("views")); menuMgr.add(openPropertyAction); menuMgr.add(openOutlineAction); menuMgr.add(new Separator("generate")); menuMgr.add(new Separator("additions")); viewer.setContextMenu(menuMgr); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer).setParent(getCommonKeyHandler())); } |
00
| Code Sample 1:
public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } }
Code Sample 2:
public static String getUserPass(String user) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(user.getBytes()); byte[] hash = digest.digest(); System.out.println("Returning user pass:" + hash); return hash.toString(); } |
00
| Code Sample 1:
public static void v2ljastaVeebileht(String s) throws IOException { URL url = new URL(s); InputStream is = url.openConnection().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } }
Code Sample 2:
protected InputStream getInputStream() throws IOException { if (source instanceof URL) { URL url = (URL) source; location = url.toString(); return url.openStream(); } else if (source instanceof File) { location = ((File) source).getAbsolutePath(); return new FileInputStream((File) source); } else if (source instanceof String) { location = (String) source; return new FileInputStream((String) source); } else if (source instanceof InputStream) { return (InputStream) source; } return null; } |
11
| Code Sample 1:
public void copyFilesIntoProject(HashMap<String, String> files) { Set<String> filenames = files.keySet(); for (String key : filenames) { String realPath = files.get(key); if (key.equals("fw4ex.xml")) { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + bundle.getString("Stem") + STEM_FILE_EXETENSION)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } else { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + key)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } } }
Code Sample 2:
private static final void addFile(ZipArchiveOutputStream os, File file, String prefix) throws IOException { ArchiveEntry entry = os.createArchiveEntry(file, file.getAbsolutePath().substring(prefix.length() + 1)); os.putArchiveEntry(entry); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, os); fis.close(); os.closeArchiveEntry(); } |
11
| Code Sample 1:
public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
Code Sample 2:
@Test public void testStandardTee() throws Exception { final byte[] test = "test".getBytes(); final InputStream source = new ByteArrayInputStream(test); final ByteArrayOutputStream destination1 = new ByteArrayOutputStream(); final ByteArrayOutputStream destination2 = new ByteArrayOutputStream(); final TeeOutputStream tee = new TeeOutputStream(destination1, destination2); org.apache.commons.io.IOUtils.copy(source, tee); tee.close(); assertArrayEquals("the two arrays are equals", test, destination1.toByteArray()); assertArrayEquals("the two arrays are equals", test, destination2.toByteArray()); assertEquals("byte count", test.length, tee.getSize()); } |
11
| Code Sample 1:
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); } }
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 String getSummaryText() { if (summaryText == null) { for (Iterator iter = xdcSources.values().iterator(); iter.hasNext(); ) { XdcSource source = (XdcSource) iter.next(); File packageFile = new File(source.getFile().getParentFile(), "xdc-package.html"); if (packageFile.exists()) { Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { summaryText = buf.substring(pos1 + 6, pos2); } else { summaryText = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); summaryText = ""; } catch (IOException e) { LOG.error(e.getMessage(), e); summaryText = ""; } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } break; } else { summaryText = ""; } } } return summaryText; }
Code Sample 2:
private void refresh(String val) { HttpHost targetHost = new HttpHost("localhost", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); BasicHttpContext localcontext = new BasicHttpContext(); String searchString = val.trim().replaceAll("\\s+", "+"); HttpGet httpget = new HttpGet("/geoserver/rest/gazetteer-search/result.json?q=" + searchString); try { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); String responseText = ""; if (entity != null) { responseText = new String(EntityUtils.toByteArray(entity)); } else { responseText = "Fail"; } JSONObject responseJson = JSONObject.fromObject(responseText); JSONObject search = responseJson.getJSONObject("org.ala.rest.GazetteerSearch"); JSONArray results = search.getJSONObject("results").getJSONArray("org.ala.rest.SearchResultItem"); Iterator it = getItems().iterator(); for (int i = 0; i < results.size(); i++) { String itemString = (String) results.getJSONObject(i).get("name"); if (it != null && it.hasNext()) { ((Comboitem) it.next()).setLabel(itemString); } else { it = null; new Comboitem(itemString).setParent(this); } } while (it != null && it.hasNext()) { it.next(); it.remove(); } } catch (Exception e) { } } |
00
| Code Sample 1:
private void copyResource(String resource, File targetDir) { InputStream is = FragmentFileSetTest.class.getResourceAsStream(resource); Assume.assumeNotNull(is); int i = resource.lastIndexOf("/"); String filename; if (i == -1) { filename = resource; } else { filename = resource.substring(i + 1); } try { FileOutputStream fos = new FileOutputStream(new File(targetDir, filename)); IOUtils.copy(is, fos); fos.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } }
Code Sample 2:
public String generateDigest(String password, String saltHex, String algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsIgnoreCase("crypt")) { return "{CRYPT}" + UnixCrypt.crypt(password); } else if (algorithm.equalsIgnoreCase("sha")) { algorithm = "SHA-1"; } else if (algorithm.equalsIgnoreCase("md5")) { algorithm = "MD5"; } MessageDigest msgDigest = MessageDigest.getInstance(algorithm); byte[] salt = {}; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (algorithm.startsWith("SHA")) { label = (salt.length > 0) ? "{SSHA}" : "{SHA}"; } else if (algorithm.startsWith("MD5")) { label = (salt.length > 0) ? "{SMD5}" : "{MD5}"; } msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt))); return digest.toString(); } |
00
| Code Sample 1:
@Override public void downloadByUUID(final UUID uuid, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (!exportsInProgress.containsKey(uuid)) { throw new IllegalStateException("No download with UUID: " + uuid); } final File compressedFile = exportsInProgress.get(uuid).file; logger.debug("File size: " + compressedFile.length()); OutputStream output = null; InputStream fileInputStream = null; try { output = response.getOutputStream(); prepareResponse(request, response, compressedFile); fileInputStream = new FileInputStream(compressedFile); IOUtils.copy(fileInputStream, output); output.flush(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(output); } }
Code Sample 2:
public Attributes getAttributes() throws SchemaViolationException, NoSuchAlgorithmException, UnsupportedEncodingException { BasicAttributes outAttrs = new BasicAttributes(true); BasicAttribute oc = new BasicAttribute("objectclass", "inetOrgPerson"); oc.add("organizationalPerson"); oc.add("person"); outAttrs.put(oc); if (lastName != null && firstName != null) { outAttrs.put("sn", lastName); outAttrs.put("givenName", firstName); outAttrs.put("cn", firstName + " " + lastName); } else { throw new SchemaViolationException("user must have surname"); } if (password != null) { MessageDigest sha = MessageDigest.getInstance("md5"); sha.reset(); sha.update(password.getBytes("utf-8")); byte[] digest = sha.digest(); String hash = Base64.encodeBase64String(digest); outAttrs.put("userPassword", "{MD5}" + hash); } if (email != null) { outAttrs.put("mail", email); } return (Attributes) outAttrs; } |
11
| Code Sample 1:
public static boolean copy(final File from, final File to) { if (from.isDirectory()) { to.mkdirs(); for (final String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { if (COPY_DEBUG) { System.out.println("Failed to copy " + name + " from " + from + " to " + to); } return false; } } } else { try { final FileInputStream is = new FileInputStream(from); final FileChannel ifc = is.getChannel(); final FileOutputStream os = makeFile(to); if (USE_NIO) { final FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (final IOException ex) { if (COPY_DEBUG) { System.out.println("Failed to copy " + from + " to " + to + ": " + ex); } return false; } } final long time = from.lastModified(); setLastModified(to, time); final long newtime = to.lastModified(); if (COPY_DEBUG) { if (newtime != time) { System.out.println("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime)); to.setLastModified(time); final long morenewtime = to.lastModified(); return false; } else { System.out.println("Timestamp for " + to + " set successfully."); } } return time == newtime; }
Code Sample 2:
public static boolean copyFile(File src, File target) throws IOException { if (src == null || target == null || !src.exists()) return false; if (!target.exists()) if (!createNewFile(target)) return false; InputStream ins = new BufferedInputStream(new FileInputStream(src)); OutputStream ops = new BufferedOutputStream(new FileOutputStream(target)); int b; while (-1 != (b = ins.read())) ops.write(b); Streams.safeClose(ins); Streams.safeFlush(ops); Streams.safeClose(ops); return target.setLastModified(src.lastModified()); } |
00
| Code Sample 1:
private static String webService(String strUrl) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(strUrl); InputStream input = url.openStream(); String sCurrentLine = ""; InputStreamReader read = new InputStreamReader(input, "utf-8"); BufferedReader l_reader = new java.io.BufferedReader(read); while ((sCurrentLine = l_reader.readLine()) != null) { buffer.append(sCurrentLine); } return buffer.toString(); } catch (Exception e) { e.printStackTrace(); return null; } }
Code Sample 2:
public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); } |
00
| Code Sample 1:
public MemoryTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
Code Sample 2:
public static GenericDocumentTransformer<? extends GenericDocument> getTranformer(URL url) throws IOException { setDefaultImplementation(); if ("text/xml".equals(url.openConnection().getContentType()) || "application/xml".equals(url.openConnection().getContentType())) { return null; } else if ("text/html".equals(url.openConnection().getContentType())) { return null; } return null; } |
00
| Code Sample 1:
public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
Code Sample 2:
public void writeToStream(String urlString, OutputStream os) { BufferedInputStream input = null; try { URL url = new URL(urlString); System.out.println("Opening stream:" + url.toString()); input = new BufferedInputStream(url.openStream(), 4 * 1024 * 1024); byte[] data = new byte[102400]; int read; while ((read = input.read(data)) != -1) { os.write(data, 0, read); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
11
| Code Sample 1:
public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } }
Code Sample 2:
protected HttpResponseImpl makeRequest(final HttpMethod m, final String requestId) { try { HttpResponseImpl ri = new HttpResponseImpl(); ri.setRequestMethod(m); ri.setResponseCode(_client.executeMethod(m)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(m.getResponseBodyAsStream(), bos); ri.setResponseBody(bos.toByteArray()); notifyOfRequestSuccess(requestId, m, ri); return ri; } catch (HttpException ex) { notifyOfRequestFailure(requestId, m, ex); } catch (IOException ex) { notifyOfRequestFailure(requestId, m, ex); } return null; } |
00
| Code Sample 1:
public boolean authenticate(String plaintext) throws NoSuchAlgorithmException { String[] passwordParts = this.password.split("\\$"); md = MessageDigest.getInstance("SHA-1"); md.update(passwordParts[1].getBytes()); isAuthenticated = toHex(md.digest(plaintext.getBytes())).equalsIgnoreCase(passwordParts[2]); return isAuthenticated; }
Code Sample 2:
public static void loadPoFile(URL url) { states state = states.IDLE; String msgCtxt = ""; String msgId = ""; String msgStr = ""; try { if (url == null) return; InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); String strLine; while ((strLine = br.readLine()) != null) { if (strLine.startsWith("msgctxt")) { if (state != states.MSGCTXT) msgCtxt = ""; state = states.MSGCTXT; strLine = strLine.substring(7).trim(); } if (strLine.startsWith("msgid")) { if (state != states.MSGID) msgId = ""; state = states.MSGID; strLine = strLine.substring(5).trim(); } if (strLine.startsWith("msgstr")) { if (state != states.MSGSTR) msgStr = ""; state = states.MSGSTR; strLine = strLine.substring(6).trim(); } if (!strLine.startsWith("\"")) { state = states.IDLE; msgCtxt = ""; msgId = ""; msgStr = ""; } else { if (state == states.MSGCTXT) { msgCtxt += format(strLine); } if (state == states.MSGID) { if (msgId.isEmpty()) { if (!msgCtxt.isEmpty()) { msgId = msgCtxt + "|"; msgCtxt = ""; } } msgId += format(strLine); } if (state == states.MSGSTR) { msgCtxt = ""; msgStr += format(strLine); if (!msgId.isEmpty()) messages.setProperty(msgId, msgStr); } } } in.close(); } catch (IOException e) { Logger.logError(e, "Error loading message.po."); } } |
00
| Code Sample 1:
public static String md5EncodeString(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (s == null) return null; if (StringUtils.isBlank(s)) return ""; MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes("UTF-8")); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); }
Code Sample 2:
public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } } |
11
| Code Sample 1:
public String calculateProjectMD5(String scenarioName) throws Exception { Scenario s = ScenariosManager.getInstance().getScenario(scenarioName); s.loadParametersAndValues(); String scenarioMD5 = calculateScenarioMD5(s); Map<ProjectComponent, String> map = getProjectMD5(new ProjectComponent[] { ProjectComponent.resources, ProjectComponent.classes, ProjectComponent.suts, ProjectComponent.libs }); map.put(ProjectComponent.currentScenario, scenarioMD5); MessageDigest md = MessageDigest.getInstance("MD5"); Iterator<String> iter = map.values().iterator(); while (iter.hasNext()) { md.update(iter.next().getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
Code Sample 2:
@SuppressWarnings("unused") private static int chkPasswd(final String sInputPwd, final String sSshaPwd) { assert sInputPwd != null; assert sSshaPwd != null; int r = ERR_LOGIN_ACCOUNT; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); assert ba.length >= FIXED_HASH_SIZE; byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sInputPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); if (MessageDigest.isEqual(hash, baPwdHash)) { r = ERR_LOGIN_OK; } } catch (Exception exc) { exc.printStackTrace(); } return r; } |
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 void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } } |
11
| Code Sample 1:
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); ServletContext ctx = getServletContext(); RequestDispatcher rd = ctx.getRequestDispatcher(SETUP_JSP); HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(true); session.setAttribute(ERROR_TAG, "You need to have run the Sniffer before running " + "the Grinder. Go to <a href=\"/index.jsp\">the start page</a> " + " to run the Sniffer."); rd = ctx.getRequestDispatcher(ERROR_JSP); } else { session.setMaxInactiveInterval(-1); String pValue = request.getParameter(ACTION_TAG); if (pValue != null && pValue.equals(START_TAG)) { rd = ctx.getRequestDispatcher(WAIT_JSP); int p = 1; int t = 1; int c = 1; try { p = Integer.parseInt(request.getParameter("procs")); p = p > MAX_PROCS ? MAX_PROCS : p; } catch (NumberFormatException e) { } try { t = Integer.parseInt(request.getParameter("threads")); t = t > MAX_THREADS ? MAX_THREADS : t; } catch (NumberFormatException e) { } try { c = Integer.parseInt(request.getParameter("cycles")); c = c > MAX_CYCLES ? MAX_CYCLES : c; } catch (NumberFormatException e) { } try { String dirname = (String) session.getAttribute(OUTPUT_TAG); File workdir = new File(dirname); (new File(dirname + File.separator + LOG_DIR)).mkdir(); FileInputStream gpin = new FileInputStream(GPROPS); FileOutputStream gpout = new FileOutputStream(dirname + File.separator + GPROPS); copyBytes(gpin, gpout); gpin.close(); InitialContext ictx = new InitialContext(); Boolean isSecure = (Boolean) session.getAttribute(SECURE_TAG); if (isSecure.booleanValue()) { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpsPlugin" + "\n").getBytes()); String certificate = (String) ictx.lookup(CERTIFICATE); String password = (String) ictx.lookup(PASSWORD); gpout.write(("grinder.plugin.parameter.clientCert=" + certificate + "\n").getBytes()); gpout.write(("grinder.plugin.parameter.clientCertPassword=" + password + "\n").getBytes()); } else { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpPlugin\n").getBytes()); } gpout.write(("grinder.processes=" + p + "\n").getBytes()); gpout.write(("grinder.threads=" + t + "\n").getBytes()); gpout.write(("grinder.cycles=" + c + "\n").getBytes()); gpin = new FileInputStream(dirname + File.separator + SNIFFOUT); copyBytes(gpin, gpout); gpin.close(); gpout.close(); String classpath = (String) ictx.lookup(CLASSPATH); String cmd[] = new String[JAVA_PROCESS.length + 1 + GRINDER_PROCESS.length]; int i = 0; int n = JAVA_PROCESS.length; System.arraycopy(JAVA_PROCESS, 0, cmd, i, n); cmd[n] = classpath; i = n + 1; n = GRINDER_PROCESS.length; System.arraycopy(GRINDER_PROCESS, 0, cmd, i, n); for (int j = 0; j < cmd.length; ++j) { System.out.print(cmd[j] + " "); } Process proc = Runtime.getRuntime().exec(cmd, null, workdir); session.setAttribute(PROCESS_TAG, proc); } catch (NamingException e) { e.printStackTrace(); session.setAttribute(ERROR_MSG_TAG, e.toString()); session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(ERROR_JSP); } catch (Throwable e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } else if (pValue != null && pValue.equals(CHECK_TAG)) { boolean finished = true; try { Process p = (Process) session.getAttribute(PROCESS_TAG); int result = p.exitValue(); } catch (IllegalThreadStateException e) { finished = false; } if (finished) { session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(RESULTS_JSP); } else { rd = ctx.getRequestDispatcher(WAIT_JSP); } } try { rd.forward(request, response); } catch (ServletException e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } }
Code Sample 2:
private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } } |
11
| Code Sample 1:
public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; }
Code Sample 2:
public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; } |
11
| Code Sample 1:
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } }
Code Sample 2:
private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); } |
11
| Code Sample 1:
static byte[] getPassword(final String name, final String password) { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(name.getBytes()); messageDigest.update(password.getBytes()); return messageDigest.digest(); } catch (final NoSuchAlgorithmException e) { throw new JobException(e); } }
Code Sample 2:
public static String calcResponse(String ha1, String nonce, String nonceCount, String cnonce, String qop, String method, String uri) throws FatalException, MD5DigestException { MD5Encoder encoder = new MD5Encoder(); String ha2 = null; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new FatalException(e); } if (method == null || uri == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "method or uri"); } if (qop != null && qop.equals("auth-int")) { throw new MD5DigestException(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); } if (nonce == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce"); } if (qop != null && (qop.equals("auth") || qop.equals("auth-int"))) { if (nonceCount == null || cnonce == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nc or cnonce"); } } md5.update((method + ":" + uri).getBytes()); ha2 = encoder.encode(md5.digest()); md5.update((ha1 + ":" + nonce + ":").getBytes()); if (qop != null && (qop.equals("auth") || qop.equals("auth-int"))) { md5.update((nonceCount + ":" + cnonce + ":" + qop + ":").getBytes()); } md5.update(ha2.getBytes()); String response = encoder.encode(md5.digest()); return response; } |
00
| Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
public void process() { try { update("Shutdown knowledge base ...", 0); DBHelper.shutdownDB(); update("Shutdown knowledge base ...", 9); String zipDir = P.DIR.getPKBDataPath(); update("Backup in progress ...", 10); List<String> fileList = getFilesToZip(zipDir); File file = new File(fileName); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file)); byte[] readBuffer = new byte[2156]; int bytesIn = 0; for (int i = 0; i < fileList.size(); i++) { String filePath = fileList.get(i); File f = new File(filePath); FileInputStream fis = new FileInputStream(f); String zipEntryName = f.getPath().substring(zipDir.length() + 1); ZipEntry anEntry = new ZipEntry(zipEntryName); zout.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zout.write(readBuffer, 0, bytesIn); } fis.close(); int percentage = (int) Math.round((i + 1) * 80.0 / fileList.size()); update("Backup in progress ...", 10 + percentage); } zout.close(); update("Restart knowledge base ...", 91); DBHelper.startDB(); update("Backup is done!", 100); } catch (Exception ex) { ex.printStackTrace(); update("Error occurs during backup!", 100); } } |
11
| Code Sample 1:
private void checkRoundtrip(byte[] content) throws Exception { InputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(); CodecUtil.encodeQuotedPrintableBinary(in, out); in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray())); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); assertEquals(content, out.toByteArray()); }
Code Sample 2:
public static void copy(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } |
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 void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { logger.error(Logger.SECURITY_FAILURE, "Problem decoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
static void reopen(MJIEnv env, int objref) throws IOException { int fd = env.getIntField(objref, "fd"); long off = env.getLongField(objref, "off"); if (content.get(fd) == null) { int mode = env.getIntField(objref, "mode"); int fnRef = env.getReferenceField(objref, "fileName"); String fname = env.getStringObject(fnRef); if (mode == FD_READ) { FileInputStream fis = new FileInputStream(fname); FileChannel fc = fis.getChannel(); fc.position(off); content.set(fd, fis); } else if (mode == FD_WRITE) { FileOutputStream fos = new FileOutputStream(fname); FileChannel fc = fos.getChannel(); fc.position(off); content.set(fd, fos); } else { env.throwException("java.io.IOException", "illegal mode: " + mode); } } } |
00
| Code Sample 1:
public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } }
Code Sample 2:
private void readFromStorableInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); StorableInput input = new StorableInput(stream); fDrawing.release(); fDrawing = (Drawing) input.readStorable(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error:" + e); } } |
00
| Code Sample 1:
protected BufferedImage handleKBRException() { if (params.uri.startsWith("http://mara.kbr.be/kbrImage/CM/") || params.uri.startsWith("http://mara.kbr.be/kbrImage/maps/") || params.uri.startsWith("http://opteron2.kbr.be/kp/viewer/")) try { URLConnection connection = new URL(params.uri).openConnection(); String url = "get_image.php?intId="; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String aux = null; while ((aux = reader.readLine()) != null) { if (aux.indexOf(url) != -1) { aux = aux.substring(aux.indexOf(url)); url = "http://mara.kbr.be/kbrImage/" + aux.substring(0, aux.indexOf("\"")); break; } } connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e) { try { String url = "http://mara.kbr.be/xlimages/maps/thumbnails" + params.uri.substring(params.uri.lastIndexOf("/")).replace(".imgf", ".jpg"); if (url != null) { URLConnection connection = new URL(url).openConnection(); return processNewUri(connection); } } catch (Exception e2) { } } return null; }
Code Sample 2:
public void fetchKey() throws IOException { String strurl = MessageFormat.format(keyurl, new Object[] { username, secret, login, session }); StringBuffer result = new StringBuffer(); BufferedReader reader = null; URL url = null; try { url = new URL(strurl); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { result.append(line); } } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } Pattern p = Pattern.compile("<key>(.*)</key>"); Matcher m = p.matcher(result.toString()); if (m.matches()) { this.key = m.group(1); } } |
00
| Code Sample 1:
public static byte[] findHead(String url) { byte[] result = new byte[0]; InputStream in = null; try { in = new URL(appendSlash(url)).openStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = in.read(buffer)) != -1) { byte[] temp = new byte[result.length + len]; System.arraycopy(result, 0, temp, 0, result.length); System.arraycopy(buffer, 0, temp, result.length, len); result = temp; if (DEBUG) { log.debug(String.format("len=%d, result.length=%d", len, result.length)); } if (result.length > 4096) { break; } if (result.length > 1024) { String s = new String(result).replaceAll("\\s+", " "); Matcher m = P_HEAD.matcher(s); if (m.find()) { break; } } } } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { if (null != in) in.close(); } catch (IOException e) { } } return result; }
Code Sample 2:
public static void doGet(HttpServletRequest request, HttpServletResponse response, CollOPort colloport, PrintStream out) throws ServletException, IOException { response.addDateHeader("Expires", System.currentTimeMillis() - 86400); String id = request.getParameter("id"); String url_index = request.getParameter("url_index"); int url_i; try { url_i = Integer.parseInt(url_index); } catch (NumberFormatException nfe) { url_i = 0; } Summary summary = colloport.getSummary(id); String filename = request.getPathInfo(); if (filename != null && filename.length() > 0) { filename = filename.substring(1); } String includeURLAll = summary.getIncludeURL(); String includeURLs[] = includeURLAll.split(" "); String includeURL = includeURLs[url_i]; if (includeURL != null && includeURL.length() > 0) { if (filename.indexOf(":") > 0) { includeURL = ""; } else if (filename.startsWith("/")) { includeURL = includeURL.substring(0, includeURL.indexOf("/")); } else if (!includeURL.endsWith("/") && includeURL.indexOf(".") > 0) { includeURL = includeURL.substring(0, includeURL.lastIndexOf("/") + 1); } URL url = null; try { url = new URL(includeURL + response.encodeURL(filename)); } catch (MalformedURLException mue) { System.out.println(mue); } URLConnection conn = null; if (url != null) { try { conn = url.openConnection(); } catch (IOException ioe) { System.out.println(ioe); } } if (conn != null) { String contentType = conn.getContentType(); String contentDisposition; if (contentType == null) { contentType = "application/x-java-serialized-object"; contentDisposition = "attachment;filename=\"" + filename + "\""; } else { contentDisposition = "inline;filename=\"" + filename + "\""; } response.setHeader("content-disposition", contentDisposition); response.setContentType(contentType); try { InputStream inputStream = conn.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) >= 0) { response.getOutputStream().write(buffer, 0, bytesRead); } inputStream.close(); } catch (IOException ioe) { response.setContentType("text/plain"); ioe.printStackTrace(out); } if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } } } |
11
| Code Sample 1:
public static void addClasses(URL url) { BufferedReader reader = null; String line; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith(";")) { continue; } try { classes.add(Class.forName(line, true, cl)); } catch (Throwable t) { } } } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } }
Code Sample 2:
public String GetMemberName(String id) { String name = null; try { String line; URL url = new URL(intvasmemberDeatails + "?CID=" + id); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { name = line; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String[] parts = name.split(" "); rating = parts[2]; return parts[0] + " " + parts[1]; } |
00
| Code Sample 1:
public Model read(String uri, String base, String lang) { try { URL url = new URL(uri); return read(url.openStream(), base, lang); } catch (IOException e) { throw new OntologyException("I/O error while reading from uri " + uri); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public static boolean copyFile(File soureFile, File destFile) { boolean copySuccess = false; if (soureFile != null && destFile != null && soureFile.exists()) { try { new File(destFile.getParent()).mkdirs(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(soureFile)); for (int currentByte = in.read(); currentByte != -1; currentByte = in.read()) out.write(currentByte); in.close(); out.close(); copySuccess = true; } catch (Exception e) { copySuccess = false; } } return copySuccess; }
Code Sample 2:
public void unpack(File destDirectory, boolean delete) { if (delete) delete(destDirectory); if (destDirectory.exists()) throw new ContentPackageException("Destination directory already exists."); this.destDirectory = destDirectory; this.manifestFile = new File(destDirectory, MANIFEST_FILE_NAME); try { if (zipInputStream == null) zipInputStream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { File destFile = new File(destDirectory, zipEntry.getName()); destFile.getParentFile().mkdirs(); if (!zipEntry.isDirectory()) { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int length; while ((length = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) output.write(buffer, 0, length); output.close(); zipInputStream.closeEntry(); } } zipInputStream.close(); } catch (IOException ex) { throw new ContentPackageException(ex); } } |
11
| Code Sample 1:
public boolean setDeleteCliente(int IDcliente) { boolean delete = false; try { stm = conexion.prepareStatement("delete clientes where IDcliente='" + IDcliente + "'"); stm.executeUpdate(); conexion.commit(); delete = true; } catch (SQLException e) { System.out.println("Error en la eliminacion del registro en tabla clientes " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return delete = false; } return delete; }
Code Sample 2:
private String addEqError(EquivalencyException e, int namespaceId) throws SQLException { List l = Arrays.asList(e.getListOfEqErrors()); int size = l.size(); String sql = getClassifyDAO().getStatement(TABLE_KEY, "ADD_CLASSIFY_EQ_ERROR"); PreparedStatement ps = null; conn.setAutoCommit(false); try { deleteCycleError(namespaceId); deleteEqError(namespaceId); long conceptGID1 = -1; long conceptGID2 = -1; ps = conn.prepareStatement(sql); for (int i = 0; i < l.size(); i++) { EqError error = (EqError) l.get(i); ConceptRef ref1 = error.getConcept1(); ConceptRef ref2 = error.getConcept2(); conceptGID1 = getConceptGID(ref1, namespaceId); conceptGID2 = getConceptGID(ref2, namespaceId); ps.setLong(1, conceptGID1); ps.setLong(2, conceptGID2); ps.setInt(3, namespaceId); int result = ps.executeUpdate(); if (result == 0) { throw new SQLException("unable to add eq error: " + sql); } } conn.commit(); return "EquivalencyException: Concept: " + conceptGID1 + " namespaceId: " + namespaceId + " conceptGID2: " + conceptGID2 + ((size > 1) ? "...... more" : ""); } catch (SQLException sqle) { conn.rollback(); throw sqle; } catch (Exception ex) { conn.rollback(); throw toSQLException(ex, "cannot add eq errors"); } finally { conn.setAutoCommit(true); if (ps != null) { ps.close(); } } } |
00
| Code Sample 1:
public static boolean BMPfromURL(URL url, MainClass mc) { TextField TF = mc.TF; PixCanvas canvas = mc.canvas; Image image = null; try { image = Toolkit.getDefaultToolkit().createImage(BMPReader.getBMPImage(url.openStream())); } catch (IOException e) { return false; } if (image == null) { TF.setText("Error not a typical image BMP format"); return false; } MediaTracker tr = new MediaTracker(canvas); tr.addImage(image, 0); try { tr.waitForID(0); } catch (InterruptedException e) { } ; if (tr.isErrorID(0)) { Tools.debug(OpenOther.class, "Tracker error " + tr.getErrorsAny().toString()); return false; } PixObject po = new PixObject(url, image, canvas, false, null); mc.vimages.addElement(po); TF.setText(url.toString()); canvas.repaint(); return true; }
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:
private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
00
| Code Sample 1:
public ForkJavaProject(String projectName, Class<?> activatorClass) { this.activatorClass = activatorClass; try { IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot(); this.prj = rootWorkspace.getProject(projectName); if (this.prj.exists()) { this.prj.delete(true, true, new NullProgressMonitor()); } this.prj.create(new NullProgressMonitor()); this.prj.open(new NullProgressMonitor()); IProjectDescription description = this.prj.getDescription(); description.setNatureIds(new String[] { "org.eclipse.jdt.core.javanature" }); this.prj.setDescription(description, new NullProgressMonitor()); createProjectDir(Constants.Dirs.DIR_MAIN_JAVA); createProjectDir(Constants.Dirs.DIR_CONFIG); createProjectDir(Constants.Dirs.DIR_MAIN_RESOURCES); createProjectDir(Constants.Dirs.DIR_MODELS); createProjectDir(Constants.Dirs.DIR_TESTS_JAVA); createProjectDir(Constants.Dirs.DIR_TESTS_RESOURCES); createProjectDir(Constants.Dirs.DIR_CLASSES); createProjectDir(Constants.Dirs.DIR_LIB); this.prj.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); this.javaProject = JavaCore.create(this.prj); if (this.javaProject.exists() && !this.javaProject.isOpen()) { this.javaProject.open(new NullProgressMonitor()); } File javaHome = new File(System.getProperty("java.home")); IPath jreLibPath = new Path(javaHome.getPath()).append("lib").append("rt.jar"); this.javaProject.setOutputLocation(prj.getFolder(Constants.Dirs.DIR_CLASSES).getFullPath(), new NullProgressMonitor()); JavaCore.setClasspathVariable("JRE_LIB", jreLibPath, new NullProgressMonitor()); this.javaProject.setRawClasspath(getProjectClassPath(), new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().getLog().log(new Status(Status.ERROR, Activator.PLUGIN_ID, "An exception has been thrown while creating Project", e)); } }
Code Sample 2:
public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } } |
00
| Code Sample 1:
public byte[] uniqueID(String name, String topic) { String key; byte[] id; synchronized (cache_) { key = name + "|" + topic; id = (byte[]) cache_.get(key); if (id == null) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); md.update(name.getBytes()); md.update(topic.getBytes()); id = md.digest(); cache_.put(key, id); if (debug_) { System.out.println("Cached " + key + " [" + id[0] + "," + id[1] + ",...]"); } } catch (NoSuchAlgorithmException e) { throw new Error("SHA not available!"); } } } return id; }
Code Sample 2:
public void removerTopicos(Topicos topicos) throws ClassNotFoundException, SQLException { this.criaConexao(false); String sql = "DELETE FROM \"Topicos\" " + " WHERE \"id_Topicos\" = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, topicos.getIdTopicos()); stmt.executeUpdate(); connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } } |
00
| Code Sample 1:
@SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } }
Code Sample 2:
public void testRedirectWithCookie() throws Exception { String host = "localhost"; int port = this.localServer.getServicePort(); this.localServer.register("*", new BasicRedirectService(host, port)); DefaultHttpClient client = new DefaultHttpClient(); CookieStore cookieStore = new BasicCookieStore(); client.setCookieStore(cookieStore); BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setDomain("localhost"); cookie.setPath("/"); cookieStore.addCookie(cookie); HttpContext context = new BasicHttpContext(); HttpGet httpget = new HttpGet("/oldlocation/"); HttpResponse response = client.execute(getServerHttp(), httpget, context); HttpEntity e = response.getEntity(); if (e != null) { e.consumeContent(); } HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); Header[] headers = reqWrapper.getHeaders(SM.COOKIE); assertEquals("There can only be one (cookie)", 1, headers.length); } |
11
| Code Sample 1:
private boolean copy_to_file_io(File src, File dst) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); is = new BufferedInputStream(is); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); byte buffer[] = new byte[1024 * 64]; int read; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } return true; } finally { try { if (is != null) is.close(); } catch (IOException e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (IOException e) { Debug.debug(e); } } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
11
| Code Sample 1:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
Code Sample 2:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } |
11
| Code Sample 1:
public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
Code Sample 2:
public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException { File d = new File(dir); if (!d.isDirectory()) throw new IllegalArgumentException("Not a directory: " + dir); String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); } |
11
| Code Sample 1:
public static void copyTo(File inFile, File outFile) throws IOException { char[] cbuff = new char[32768]; BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); int readedBytes = 0; long absWrittenBytes = 0; while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1) { writer.write(cbuff, 0, readedBytes); absWrittenBytes += readedBytes; } reader.close(); writer.close(); }
Code Sample 2:
public void init(File file) { InputStream is = null; ByteArrayOutputStream os = null; try { is = new FileInputStream(file); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); } catch (Throwable e) { throw new VisualizerEngineException("Unexcpected exception while reading MDF file", e); } if (simulationEngine != null) simulationEngine.stopSimulation(); simulationEngine = new TrafficAsynchSimulationEngine(); simulationEngine.init(MDFReader.read(os.toByteArray())); simulationEngineThread = null; } |
11
| Code Sample 1:
public static String gerarDigest(String mensagem) { String mensagemCriptografada = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); System.out.println("Mensagem original: " + mensagem); md.update(mensagem.getBytes()); byte[] digest = md.digest(); mensagemCriptografada = converterBytesEmHexa(digest); } catch (Exception e) { e.printStackTrace(); } return mensagemCriptografada; }
Code Sample 2:
private String md5(String txt) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(txt.getBytes(), 0, txt.length()); return new BigInteger(1, m.digest()).toString(16); } catch (Exception e) { return "BAD MD5"; } } |
11
| Code Sample 1:
public static String makeMD5(String pin) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pin.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { hexString.append(Integer.toHexString(0xFF & hash[i])); } return hexString.toString(); } catch (Exception e) { return null; } }
Code Sample 2:
public static String getMD5(String text) { if (text == null) { return null; } String result = null; try { MessageDigest md5 = MessageDigest.getInstance(ALG_MD5); md5.update(text.getBytes(ENCODING)); result = "" + new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } |
11
| Code Sample 1:
public static boolean copy(InputStream is, File file) { try { IOUtils.copy(is, new FileOutputStream(file)); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } }
Code Sample 2:
public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } } |
00
| Code Sample 1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
Code Sample 2:
@TestTargetNew(level = TestLevel.COMPLETE, notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128", method = "getInputStream", args = { }) public void test_getInputStream_DeleteJarFileUsingURLConnection() throws Exception { String jarFileName = ""; String entry = "text.txt"; String cts = System.getProperty("java.io.tmpdir"); File tmpDir = new File(cts); File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir); jarFileName = jarFile.getPath(); FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName); JarOutputStream out = new JarOutputStream(new BufferedOutputStream(jarFileOutputStream)); JarEntry jarEntry = new JarEntry(entry); out.putNextEntry(jarEntry); out.write(new byte[] { 'a', 'b', 'c' }); out.close(); URL url = new URL("jar:file:" + jarFileName + "!/" + entry); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStream is = conn.getInputStream(); is.close(); assertTrue(jarFile.delete()); } |
11
| Code Sample 1:
private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { PrintUtil.prt((char) buff.get()); } } |
00
| Code Sample 1:
@Test public void unacceptableMimeTypeTest() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/alfresco/sword/deposit/company_home"); File file = new File("/Library/Application Support/Apple/iChat Icons/Planets/Mars.gif"); FileEntity entity = new FileEntity(file, "text/xml"); entity.setChunked(true); httppost.setEntity(entity); Date date = new Date(); Long time = date.getTime(); httppost.addHeader("content-disposition", "filename=x" + time + "x.gif"); System.out.println("Executing request...." + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { InputStream is = resEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = br.readLine()) != null) { if (!line.isEmpty()) System.out.println(line); } } if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); }
Code Sample 2:
public static String calculate(String str) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(str.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException ex) { return null; } } |
11
| Code Sample 1:
public synchronized String encrypt(String plaintext) { if (plaintext == null || plaintext.equals("")) { return plaintext; } String hash = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); hash = Base64.encodeBase64String(raw).replaceAll("\r\n", ""); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage()); } return hash; }
Code Sample 2:
public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { Log.error(e.getMessage(), e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); } |
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) { logger.error(Logger.SECURITY_FAILURE, "Problem encoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = new URL(System.getenv("plugg_home") + "/" + systemId); System.out.println("SystemId = " + systemId); return new InputSource(url.openStream()); } |
00
| Code Sample 1:
public static void loadFile(final URL url, final StringBuffer buffer) throws IOException { InputStream in = null; BufferedReader dis = null; try { in = url.openStream(); dis = new BufferedReader(new InputStreamReader(in)); int i; while ((i = dis.read()) != -1) { buffer.append((char) i); } } finally { closeStream(in); closeReader(dis); } }
Code Sample 2:
protected void readLockssConfigFile(URL url, List<String> peers) { PrintWriter out = null; try { out = new PrintWriter(new OutputStreamWriter(System.out, "utf8"), true); out.println("unicode-output-ready"); } catch (UnsupportedEncodingException ex) { System.out.println(ex.toString()); return; } XMLInputFactory xmlif = XMLInputFactory.newInstance(); xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE); xmlif.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE); XMLStreamReader xmlr = null; BufferedInputStream stream = null; long starttime = System.currentTimeMillis(); out.println("Starting to parse the remote config xml[" + url + "]"); int elementCount = 0; int topPropertyCounter = 0; int propertyTagLevel = 0; try { stream = new BufferedInputStream(url.openStream()); xmlr = xmlif.createXMLStreamReader(stream, "utf8"); int eventType = xmlr.getEventType(); String curElement = ""; String targetTagName = "property"; String peerListAttrName = "id.initialV3PeerList"; boolean sentinel = false; boolean valueline = false; while (xmlr.hasNext()) { eventType = xmlr.next(); switch(eventType) { case XMLEvent.START_ELEMENT: curElement = xmlr.getLocalName(); if (curElement.equals("property")) { topPropertyCounter++; propertyTagLevel++; int count = xmlr.getAttributeCount(); if (count > 0) { for (int i = 0; i < count; i++) { if (xmlr.getAttributeValue(i).equals(peerListAttrName)) { sentinel = true; out.println("!!!!!! hit the" + peerListAttrName); out.println("attr=" + xmlr.getAttributeName(i)); out.println("vl=" + xmlr.getAttributeValue(i)); out.println(">>>>>>>>>>>>>> start :property tag (" + topPropertyCounter + ") >>>>>>>>>>>>>>"); out.println(">>>>>>>>>>>>>> property tag level (" + propertyTagLevel + ") >>>>>>>>>>>>>>"); out.print(xmlr.getAttributeName(i).toString()); out.print("="); out.print("\""); out.print(xmlr.getAttributeValue(i)); out.println(""); } } } } if (sentinel && curElement.equals("value")) { valueline = true; String ipAd = xmlr.getElementText(); peers.add(ipAd); } break; case XMLEvent.CHARACTERS: break; case XMLEvent.ATTRIBUTE: if (curElement.equals(targetTagName)) { } break; case XMLEvent.END_ELEMENT: if (xmlr.getLocalName().equals("property")) { if (sentinel) { out.println("========= end of the target property element"); sentinel = false; valueline = false; } elementCount++; propertyTagLevel--; } else { } break; case XMLEvent.END_DOCUMENT: } } } catch (MalformedURLException ue) { } catch (IOException ex) { } catch (XMLStreamException ex) { } finally { if (xmlr != null) { try { xmlr.close(); } catch (XMLStreamException ex) { } } if (stream != null) { try { stream.close(); } catch (IOException ex) { } } } } |
00
| Code Sample 1:
public static String httpGet(URL url) throws Exception { URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); }
Code Sample 2:
private FTPClient getFtpClient(Entry parentEntry) throws Exception { Object[] values = parentEntry.getValues(); if (values == null) { return null; } String server = (String) values[COL_SERVER]; String baseDir = (String) values[COL_BASEDIR]; String user = (String) values[COL_USER]; String password = (String) values[COL_PASSWORD]; if (password != null) { password = getRepository().getPageHandler().processTemplate(password, false); } else { password = ""; } FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server); if (user != null) { ftpClient.login(user, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return null; } ftpClient.setFileType(FTP.IMAGE_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return ftpClient; } catch (Exception exc) { System.err.println("Could not connect to ftp server:" + exc); return null; } } |
11
| Code Sample 1:
private void simulate() throws Exception { BufferedWriter out = null; out = new BufferedWriter(new FileWriter(outFile)); out.write("#Thread\tReputation\tAction\n"); out.flush(); System.out.println("Simulate..."); File file = new File(trsDemoSimulationfile); ObtainUserReputation obtainUserReputationRequest = new ObtainUserReputation(); ObtainUserReputationResponse obtainUserReputationResponse; RateUser rateUserRequest; RateUserResponse rateUserResponse; FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String call = br.readLine(); while (call != null) { rateUserRequest = generateRateUserRequest(call); try { rateUserResponse = trsPort.rateUser(rateUserRequest); System.out.println("----------------R A T I N G-------------------"); System.out.println("VBE: " + rateUserRequest.getVbeId()); System.out.println("VO: " + rateUserRequest.getVoId()); System.out.println("USER: " + rateUserRequest.getUserId()); System.out.println("SERVICE: " + rateUserRequest.getServiceId()); System.out.println("ACTION: " + rateUserRequest.getActionId()); System.out.println("OUTCOME: " + rateUserResponse.isOutcome()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the rateUser should be true: MESSAGE=" + rateUserResponse.getMessage(), true, rateUserResponse.isOutcome()); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(null); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(rateUserRequest.getVoId()); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } call = br.readLine(); } fis.close(); br.close(); out.flush(); out.close(); }
Code Sample 2:
public static void perform(ChangeSet changes, ArchiveInputStream in, ArchiveOutputStream out) throws IOException { ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { System.out.println(entry.getName()); boolean copy = true; for (Iterator it = changes.asSet().iterator(); it.hasNext(); ) { Change change = (Change) it.next(); if (change.type() == ChangeSet.CHANGE_TYPE_DELETE) { DeleteChange delete = ((DeleteChange) change); if (entry.getName() != null && entry.getName().equals(delete.targetFile())) { copy = false; } } } if (copy) { System.out.println("Copy: " + entry.getName()); long size = entry.getSize(); out.putArchiveEntry(entry); IOUtils.copy((InputStream) in, out, (int) size); out.closeArchiveEntry(); } System.out.println("---"); } out.close(); } |
11
| Code Sample 1:
public static void copy(File srcFile, File destFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); final byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } finally { try { if (in != null) in.close(); } catch (IOException ioe) { } try { if (out != null) out.close(); } catch (IOException ioe) { } } }
Code Sample 2:
private static void cut() { File inputFile = new File(inputFileName); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print("Invalid File Name!"); System.err.flush(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.print("Invalid Char Set Name!"); System.err.flush(); System.exit(1); } switch(cutMode) { case charMode: { int outputFileIndex = 1; char[] readBuf = new char[charPerFile]; while (true) { int readCount = 0; try { readCount = in.read(readBuf); } catch (IOException e) { System.err.println("Read IO Error!"); System.err.flush(); System.exit(1); } if (-1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + "-" + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), outputCharSet)); out.write(readBuf, 0, readCount); out.flush(); out.close(); outputFileIndex++; } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } } } break; } case lineMode: { boolean isFileEnd = false; int outputFileIndex = 1; while (!isFileEnd) { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = inputFileName.substring(ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } out.println(line); ++p; } out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } break; } case htmlMode: { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat("0000"); while (!isFileEnd) { try { File outputFile = new File(prefixInputFileName + "-" + df.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); out.println("<html><head><title>" + prefixInputFileName + "-" + df.format(outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } if (line.length() > 0) out.println("<p>" + line + "</p>"); ++p; } out.println("</div><a href=\"" + prefixInputFileName + "-" + df.format(outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } try { File indexFile = new File("index.html"); PrintStream out = new PrintStream(new FileOutputStream(indexFile), false, outputCharSet); out.println("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i++) { out.println("<li><a href=\"" + prefixInputFileName + "-" + df.format(i) + "." + postfixInputFileName + "\">" + df.format(i) + "</a></li>"); } out.println("</ul></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } break; } } } |
11
| Code Sample 1:
private File prepareFileForUpload(File source, String s3key) throws IOException { File tmp = File.createTempFile("dirsync", ".tmp"); tmp.deleteOnExit(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new DeflaterOutputStream(new CryptOutputStream(new FileOutputStream(tmp), cipher, getDataEncryptionKey())); IOUtils.copy(in, out); in.close(); out.close(); return tmp; } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } |
00
| Code Sample 1:
TreeMap<Integer, Integer> initProperties(URL propurl) { String zoneFileName = null; String costFileName = null; String homesFileName = null; String jobsFileName = null; Properties props = new Properties(); try { props.loadFromXML(propurl.openStream()); zoneFileName = props.getProperty("zoneFileName"); costFileName = props.getProperty("costFileName"); homesFileName = props.getProperty("homesFileName"); jobsFileName = props.getProperty("jobsFileName"); maxiter = Integer.parseInt(props.getProperty("maxiter")); mu = Double.parseDouble(props.getProperty("mu")); theta = Double.parseDouble(props.getProperty("theta")); threshold1 = Double.parseDouble(props.getProperty("threshold1")); threshold2 = Double.parseDouble(props.getProperty("threshold2")); verbose = Boolean.parseBoolean(props.getProperty("verbose")); } catch (Exception xc) { xc.printStackTrace(); System.exit(-1); } HashSet<Integer> zoneids = SomeIO.readZoneIDs(zoneFileName); numZ = zoneids.size(); if (verbose) { System.out.println("Data:"); System.out.println(" . #zones:" + numZ); } int idx = 0; TreeMap<Integer, Integer> zonemap = new TreeMap<Integer, Integer>(); for (Integer id : zoneids) zonemap.put(id, idx++); cij = SomeIO.readMatrix(costFileName, numZ, numZ); for (int i = 0; i < numZ; i++) { double mincij = Double.POSITIVE_INFINITY; for (int j = 0; j < numZ; j++) { double v = cij.get(i, j); if ((v < mincij) && (v > 0.0)) mincij = v; } if (cij.get(i, i) == 0.0) cij.set(i, i, mincij); } setupECij(); double meanCost = 0.0; double stdCost = 0.0; for (int i = 0; i < numZ; i++) { for (int j = 0; j < numZ; j++) { double v = cij.get(i, j); meanCost += v; stdCost += v * v; } } meanCost = meanCost / (numZ * numZ); stdCost = stdCost / (numZ * numZ) - meanCost * meanCost; if (verbose) System.out.println(" . Travel costs mean=" + meanCost + " std.dev.= " + Math.sqrt(stdCost)); P = SomeIO.readZoneAttribute(numZ, homesFileName, zonemap); J = SomeIO.readZoneAttribute(numZ, jobsFileName, zonemap); double maxpj = 0.0; double sp = 0.0; double sj = 0.0; for (int i = 0; i < numZ; i++) { sp += P[i]; sj += J[i]; if (P[i] > maxpj) maxpj = P[i]; if (J[i] > maxpj) maxpj = J[i]; } if (Math.abs(sp - sj) > 1.0) { System.err.println("Error: #jobs(" + sj + ")!= #homes(" + sp + ")"); System.exit(-1); } N = sp; if (verbose) System.out.println(" . Trip tables: #jobs=#homes= " + N); return zonemap; }
Code Sample 2:
public static void concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } |
11
| Code Sample 1:
public static void copyFile(File sourceFile, File destFile, boolean overwrite) throws IOException, DirNotFoundException, FileNotFoundException, FileExistsAlreadyException { File destDir = new File(destFile.getParent()); if (!destDir.exists()) { throw new DirNotFoundException(destDir.getAbsolutePath()); } if (!sourceFile.exists()) { throw new FileNotFoundException(sourceFile.getAbsolutePath()); } if (!overwrite && destFile.exists()) { throw new FileExistsAlreadyException(destFile.getAbsolutePath()); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); }
Code Sample 2:
public static File copyFile(File from, File to) throws IOException { FileOutputStream fos = new FileOutputStream(to); FileInputStream fis = new FileInputStream(from); FileChannel foc = fos.getChannel(); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return to; } |
00
| Code Sample 1:
public void download(String ftpServer, String user, String password, String fileName, File destination) throws MalformedURLException, IOException { if (ftpServer != null && fileName != null && destination != null) { StringBuffer sb = new StringBuffer("ftp://"); if (user != null && password != null) { sb.append(user); sb.append(':'); sb.append(password); sb.append('@'); } sb.append(ftpServer); sb.append('/'); sb.append(fileName); sb.append(";type=i"); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL(sb.toString()); URLConnection urlc = url.openConnection(); bis = new BufferedInputStream(urlc.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(destination)); int i; while ((i = bis.read()) != -1) { bos.write(i); } } finally { if (bis != null) try { bis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } else { System.out.println("Input not available"); } }
Code Sample 2:
void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
00
| Code Sample 1:
private Properties getProperties(URL url) throws java.io.IOException { Properties cdrList = new Properties(); java.io.InputStream stream = url.openStream(); cdrList.load(stream); stream.close(); return cdrList; }
Code Sample 2:
public byte[] loadClassFirst(final String className) { if (className.equals("com.sun.sgs.impl.kernel.KernelContext")) { final URL url = Thread.currentThread().getContextClassLoader().getResource("com/sun/sgs/impl/kernel/KernelContext.0.9.7.class.bin"); if (url != null) { try { return StreamUtil.read(url.openStream()); } catch (IOException e) { } } throw new IllegalStateException("Unable to load KernelContext.0.9.7.class.bin"); } return null; } |
00
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void savaUserPerm(String userid, Collection user_perm_collect) throws DAOException, SQLException { ConnectionProvider cp = null; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; PrivilegeFactory factory = PrivilegeFactory.getInstance(); Operation op = factory.createOperation(); try { cp = ConnectionProviderFactory.getConnectionProvider(Constants.DATA_SOURCE); conn = cp.getConnection(); pstmt = conn.prepareStatement(DEL_USER_PERM); pstmt.setString(1, userid); pstmt.executeUpdate(); if ((user_perm_collect == null) || (user_perm_collect.size() <= 0)) { return; } else { conn.setAutoCommit(false); pstmt = conn.prepareStatement(ADD_USER_PERM); Iterator user_perm_ir = user_perm_collect.iterator(); while (user_perm_ir.hasNext()) { UserPermission userPerm = (UserPermission) user_perm_ir.next(); pstmt.setString(1, String.valueOf(userPerm.getUser_id())); pstmt.setString(2, String.valueOf(userPerm.getResource_id())); pstmt.setString(3, String.valueOf(userPerm.getResop_id())); pstmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); } } catch (Exception e) { e.printStackTrace(); conn.rollback(); throw new DAOException(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } } catch (Exception e) { } } } |
00
| Code Sample 1:
public Object sendObjectRequestToSpecifiedServer(java.lang.String serverName, java.lang.String servletName, java.lang.Object request) { Object reqxml = null; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { java.net.URL url = new java.net.URL("http://" + serverName + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream os = urlconn.getOutputStream(); java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.ObjectOutputStream dos = new java.io.ObjectOutputStream(gop); dos.writeObject(request); dos.flush(); dos.close(); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.ObjectInputStream br = new java.io.ObjectInputStream(gip); reqxml = br.readObject(); } catch (Exception exp) { exp.printStackTrace(System.out); System.out.println("Exception in Servlet Connector: " + exp); } return reqxml; }
Code Sample 2:
private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; } |
11
| Code Sample 1:
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:
@Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); } |
11
| Code Sample 1:
public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
Code Sample 2:
private static boolean prepareProbeFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "probe.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } |
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 boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
00
| Code Sample 1:
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 copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } |
00
| Code Sample 1:
@Override public BufferedImageAndBytes load(T thing) { String iurl = resolver.getUrl(thing); URL url; for (int k = 0; k < nTries; k++) { if (k > 0) { logger.debug("retry #" + k); } try { url = new URL(iurl); URLConnection connection = url.openConnection(); if (userAgent != null) { connection.setRequestProperty("User-Agent", userAgent); } InputStream is = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(40000); int b; while ((b = is.read()) != -1) { baos.write(b); } is.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage image = ImageIO.read(bais); return new BufferedImageAndBytes(image, bytes); } catch (MalformedURLException e) { continue; } catch (IOException e) { continue; } } return null; }
Code Sample 2:
private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.