label
class label
2 classes
source_code
stringlengths
398
72.9k
00
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 void postData(Reader data, Writer output) { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) solrUrl.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new PostException("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + POST_ENCODING); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, POST_ENCODING); pipe(data, writer); writer.close(); } catch (IOException e) { throw new PostException("IOException while posting data", e); } finally { if (out != null) out.close(); } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new PostException("IOException while reading response", e); } finally { if (in != null) in.close(); } } catch (IOException e) { try { fatal("Solr returned an error: " + urlc.getResponseMessage()); } catch (IOException f) { } fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e); } finally { if (urlc != null) urlc.disconnect(); } }
11
Code Sample 1: public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); } Code Sample 2: private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
00
Code Sample 1: protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } } Code Sample 2: @Override protected void removeOrphansElements() throws DatabaseException { this.getIdChache().clear(); final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); PreparedStatement preparedStatement; preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getCallElementsSchemaAndTableName() + " FROM " + this.getCallElementsSchemaAndTableName() + " LEFT JOIN " + this.getCallInvocationsSchemaAndTableName() + " ON " + this.getCallElementsSchemaAndTableName() + ".element_id = " + this.getCallInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getCallInvocationsSchemaAndTableName() + ".element_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getCallExceptionsSchemaAndTableName() + " FROM " + this.getCallExceptionsSchemaAndTableName() + " LEFT JOIN " + this.getCallInvocationsSchemaAndTableName() + " ON " + this.getCallExceptionsSchemaAndTableName() + ".exception_id = " + this.getCallInvocationsSchemaAndTableName() + ".exception_id WHERE " + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getCallPrincipalsSchemaAndTableName() + " FROM " + this.getCallPrincipalsSchemaAndTableName() + " LEFT JOIN " + this.getCallInvocationsSchemaAndTableName() + " ON " + this.getCallPrincipalsSchemaAndTableName() + ".principal_id = " + this.getCallInvocationsSchemaAndTableName() + ".principal_id WHERE " + this.getCallInvocationsSchemaAndTableName() + ".principal_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getHttpSessionElementsSchemaAndTableName() + " FROM " + this.getHttpSessionElementsSchemaAndTableName() + " LEFT JOIN " + this.getHttpSessionInvocationsSchemaAndTableName() + " ON " + this.getHttpSessionElementsSchemaAndTableName() + ".element_id = " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getJvmElementsSchemaAndTableName() + " FROM " + this.getJvmElementsSchemaAndTableName() + " LEFT JOIN " + this.getJvmInvocationsSchemaAndTableName() + " ON " + this.getJvmElementsSchemaAndTableName() + ".element_id = " + this.getJvmInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getJvmInvocationsSchemaAndTableName() + ".element_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getPersistenceEntityElementsSchemaAndTableName() + " FROM " + this.getPersistenceEntityElementsSchemaAndTableName() + " LEFT JOIN " + this.getPersistenceEntityStatisticsSchemaAndTableName() + " ON " + this.getPersistenceEntityElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceEntityStatisticsSchemaAndTableName() + ".element_id WHERE " + this.getPersistenceEntityStatisticsSchemaAndTableName() + ".element_id IS NULL "); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getPersistenceQueryElementsSchemaAndTableName() + " FROM " + this.getPersistenceQueryElementsSchemaAndTableName() + " LEFT JOIN " + this.getPersistenceQueryStatisticsSchemaAndTableName() + " ON " + this.getPersistenceQueryElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceQueryStatisticsSchemaAndTableName() + ".element_id WHERE " + this.getPersistenceQueryStatisticsSchemaAndTableName() + ".element_id IS NULL "); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getHardDiskElementsSchemaAndTableName() + " FROM " + this.getHardDiskElementsSchemaAndTableName() + " LEFT JOIN " + this.getHardDiskInvocationsSchemaAndTableName() + " ON " + this.getHardDiskElementsSchemaAndTableName() + ".element_id = " + this.getHardDiskInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getHardDiskInvocationsSchemaAndTableName() + ".element_id IS NULL "); preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error cleaning database.", e); } finally { this.releaseConnection(connection); } return; }
11
Code Sample 1: public static void zip(File srcDir, File destFile, FileFilter filter) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(destFile)); Collection<File> files = FileUtils.listFiles(srcDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (File f : files) { if (filter == null || filter.accept(f)) { FileInputStream in = FileUtils.openInputStream(f); out.putNextEntry(new ZipEntry(Util.relativePath(srcDir, f).replace('\\', '/'))); IOUtils.copyLarge(in, out); out.closeEntry(); IOUtils.closeQuietly(in); } } IOUtils.closeQuietly(out); } catch (Throwable t) { throw new IOException("Failed to create zip file", t); } finally { if (out != null) { out.flush(); IOUtils.closeQuietly(out); } } } Code Sample 2: public DoSearch(String searchType, String searchString) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerDoSearch"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "search.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + key + "&search=" + URLEncoder.encode(searchString, "UTF-8") + "&searchtype=" + URLEncoder.encode(searchType, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "search.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("entry"); int num = nodelist.getLength(); searchDocs = new String[num][3]; searchDocImageName = new String[num]; searchDocsToolTip = new String[num]; for (int i = 0; i < num; i++) { searchDocs[i][0] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename"); searchDocs[i][1] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project"); searchDocs[i][2] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid"); searchDocImageName[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename"); searchDocsToolTip[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "description"); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } System.out.println(rvalue); if (rvalue.equalsIgnoreCase("yes")) { } }
11
Code Sample 1: protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; } Code Sample 2: public static String createNormalizedJarDescriptorDigest(String path) throws Exception { String descriptor = createNormalizedDescriptor(new JarFile2(path)); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(descriptor.getBytes()); byte[] messageDigest = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
11
Code Sample 1: public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static void contentTrans(String contents, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } try { Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(contents); bufferedWriter.flush(); bufferedWriter.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); } 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 SearchHandler(String criteria, int langId) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Catalog.groovy?method=GetProductListByName&criteria=" + criteria + "&language_id=" + langId); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("product"); for (int i = 0; i < nl.getLength(); i++) { Element nodes = (Element) nl.item(i); String id = nodes.getAttribute("id").toString(); NodeList name = nodes.getElementsByTagName("name"); NodeList rank2 = nodes.getElementsByTagName("sales_rank"); NodeList price = nodes.getElementsByTagName("price"); NodeList url2 = nodes.getElementsByTagName("image_url"); String nameS = getCharacterDataFromElement((Element) name.item(0)); String rank2S = getCharacterDataFromElement((Element) rank2.item(0)); String priceS = getCharacterDataFromElement((Element) price.item(0)); String url2S = getCharacterDataFromElement((Element) url2.item(0)); list.add(new ProductShort(id, nameS, rank2S, priceS, url2S)); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public DataSet(String name, String type, URL docBase, String plotDir) { sitename = name.toUpperCase(); data = new Vector[3]; data[0] = new Vector(); data[1] = new Vector(); data[2] = new Vector(); if (type == null) return; plottype = type.toLowerCase(); String filename; filename = plotDir + sitename + "_" + plottype + ".plt.gz"; try { double total = 0; URL dataurl = new URL(docBase, filename); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String myline = readme.readLine(); if (myline == null) break; myline = myline.toLowerCase(); if (myline.startsWith("fit:")) { if (haveFit) { continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); fit = new Double[5]; String bye = (String) st.nextToken(); fit[0] = new Double((String) st.nextToken()); fit[1] = new Double((String) st.nextToken()); fit[2] = new Double((String) st.nextToken()); fit[3] = new Double((String) st.nextToken()); fit[4] = new Double((String) st.nextToken()); haveFit = true; continue; } if (myline.startsWith("decyear:")) { StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); String bye = (String) st.nextToken(); decYear = new Double((String) st.nextToken()); haveDate = true; continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); boolean ok = true; String tmp; Double[] mydbl = new Double[3]; for (int i = 0; i < 3 && ok; i++) { if (st.hasMoreTokens()) { tmp = (String) st.nextToken(); if (tmp.startsWith("X") || tmp.startsWith("x")) { ok = false; break; } else { mydbl[i] = new Double(tmp); } } else { mydbl[i] = new Double(0.0); } } if (ok) { if (mydbl[2].doubleValue() > 100) continue; total = mydbl[1].doubleValue() + total; for (int i = 0; i < 3; i++) { data[i].addElement(mydbl[i]); } } } average = total / length(); } catch (FileNotFoundException e) { System.err.println("PlotApplet: file not found: " + e); } catch (IOException e) { System.err.println("PlotApplet: error reading input file: " + e); } }
11
Code Sample 1: private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(stringToBeHashed.getBytes()); byte[] hashedKey = digest.digest(); return Util.encodeArrayToHexadecimalString(hashedKey); } Code Sample 2: public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
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 String send(String method, String url, Map<String, String> paramMap, File file, String encoding) throws HttpServerStatusException { Log.i(TAG, "url:" + url); boolean bVisitOK = false; int tryCnt = 0; String result = ""; while (!bVisitOK && (tryCnt++ < MAXTRYCNT)) { try { HttpRequestBase base = getExecuteMethod(method, url, paramMap, file); HttpResponse response = client.execute(base, localContext); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { result = readByteStream(entity.getContent(), encoding); entity.consumeContent(); } if (status == 200) { return result; } else { throw new HttpServerStatusException(status, result); } } catch (HttpServerStatusException e) { throw e; } catch (IllegalStateException e) { bVisitOK = false; Log.e(TAG, e.toString()); } catch (IOException e) { bVisitOK = false; Log.e(TAG, e.toString()); } } return result; }
00
Code Sample 1: public static boolean napiUserCheck(String user, String pass) throws TimeoutException, InterruptedException, IOException { URLConnection conn = null; InputStream in = null; URL url = new URL("http://www.napiprojekt.pl/users_check.php?nick=" + user + "&pswd=" + pass); conn = url.openConnection(Global.getProxy()); in = Timeouts.getInputStream(conn); byte[] buffer = new byte[1024]; in.read(buffer, 0, 1024); if (in != null) { in.close(); } String response = new String(buffer); if (response.indexOf("ok") == 0) { return true; } else { return false; } } Code Sample 2: private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
00
Code Sample 1: private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; } Code Sample 2: @Override public void readMessages(final Messages messages) throws LocatorException { try { final InputStream in = url.openStream(); try { final Properties properties = new Properties(); properties.load(in); messages.add(locale, properties); } finally { in.close(); } } catch (final IOException e) { throw new LocatorException("Failed to read messages from URL: " + url, e); } }
00
Code Sample 1: public static void logout4www() throws NetworkException { HttpClient client = HttpUtil.newInstance(); HttpGet get = new HttpGet(HttpUtil.KAIXIN_WWW_LOGOUT_URL); HttpUtil.setHeader(get); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } } Code Sample 2: @Override public synchronized void deletePersistenceEntityStatistics(Integer elementId, String contextName, String project, String name, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getPersistenceEntityStatisticsSchemaAndTableName() + " FROM " + this.getPersistenceEntityStatisticsSchemaAndTableName() + " INNER JOIN " + this.getPersistenceEntityElementsSchemaAndTableName() + " ON " + this.getPersistenceEntityElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceEntityStatisticsSchemaAndTableName() + ".element_id WHERE "; if (elementId != null) { queryString = queryString + " elementId = ? AND "; } if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if ((project != null)) { queryString = queryString + " project LIKE ? AND "; } if ((name != null)) { queryString = queryString + " name LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (elementId != null) { preparedStatement.setLong(indexCounter, elementId.longValue()); indexCounter = indexCounter + 1; } if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if ((project != null)) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if ((name != null)) { preparedStatement.setString(indexCounter, name); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting persistence entity statistics.", e); } finally { this.releaseConnection(connection); } }
11
Code Sample 1: private static void copier(FichierElectronique source, FichierElectronique cible) throws IOException { cible.setNom(source.getNom()); cible.setTaille(source.getTaille()); cible.setTypeMime(source.getTypeMime()); cible.setSoumetteur(source.getSoumetteur()); cible.setDateDerniereModification(source.getDateDerniereModification()); cible.setEmprunteur(source.getEmprunteur()); cible.setDateEmprunt(source.getDateEmprunt()); cible.setNumeroVersion(source.getNumeroVersion()); InputStream inputStream = source.getInputStream(); OutputStream outputStream = cible.getOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { try { inputStream.close(); } finally { outputStream.close(); } if (source instanceof FichierElectroniqueDefaut) { FichierElectroniqueDefaut fichierElectroniqueTemporaire = (FichierElectroniqueDefaut) source; fichierElectroniqueTemporaire.deleteTemp(); } } } Code Sample 2: private static void exportConfigResource(ClassLoader classLoader, String resourceName, String targetFileName) throws Exception { InputStream is = classLoader.getResourceAsStream(resourceName); FileOutputStream fos = new FileOutputStream(targetFileName, false); IOUtils.copy(is, fos); fos.close(); is.close(); }
00
Code Sample 1: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } } Code Sample 2: private int testAccesspoint(String s) throws IOException { HttpURLConnection connection = null; try { URL url = new URL(s); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode >= 500) { return 100; } else { return 0; } } finally { if (connection != null) { connection.disconnect(); } } }
11
Code Sample 1: public static void fixEol(File fin) throws IOException { File fout = File.createTempFile(fin.getName(), ".fixEol", fin.getParentFile()); FileChannel in = new FileInputStream(fin).getChannel(); if (0 != in.size()) { FileChannel out = new FileOutputStream(fout).getChannel(); byte[] eol = AStringUtilities.systemNewLine.getBytes(); ByteBuffer bufOut = ByteBuffer.allocateDirect(1024 * eol.length); boolean previousIsCr = false; ByteBuffer buf = ByteBuffer.allocateDirect(1024); while (in.read(buf) > 0) { buf.limit(buf.position()); buf.position(0); while (buf.remaining() > 0) { byte b = buf.get(); if (b == '\r') { previousIsCr = true; bufOut.put(eol); } else { if (b == '\n') { if (!previousIsCr) bufOut.put(eol); } else bufOut.put(b); previousIsCr = false; } } bufOut.limit(bufOut.position()); bufOut.position(0); out.write(bufOut); bufOut.clear(); buf.clear(); } out.close(); } in.close(); fin.delete(); fout.renameTo(fin); } Code Sample 2: protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); }
11
Code Sample 1: protected void onSubmit() { super.onSubmit(); if (!this.hasError()) { final FileUpload upload = fileUploadField.getFileUpload(); if (upload != null) { try { StringWriter xmlSourceWriter = new StringWriter(); IOUtils.copy(upload.getInputStream(), xmlSourceWriter); processSubmittedDoap(xmlSourceWriter.toString()); } catch (IOException e) { setResponsePage(new ErrorReportPage(new UserReportableException("Unable to add doap using RDF supplied", DoapFormPage.class, e))); } } } } Code Sample 2: private File uploadToTmp() { if (fileFileName == null) { return null; } File tmpFile = dataDir.tmpFile(shortname, fileFileName); log.debug("Uploading dwc archive file for new resource " + shortname + " to " + tmpFile.getAbsolutePath()); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); output = new FileOutputStream(tmpFile); IOUtils.copy(input, output); output.flush(); log.debug("Uploaded file " + fileFileName + " with content-type " + fileContentType); } catch (IOException e) { log.error(e); return null; } finally { if (output != null) { IOUtils.closeQuietly(output); } if (input != null) { IOUtils.closeQuietly(input); } } return tmpFile; }
00
Code Sample 1: public static String encrypt(String password) { String sign = password; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(sign.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } sign = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return sign; } Code Sample 2: public static void copyFile(File src, File dest) throws IOException, IllegalArgumentException { if (src.isDirectory()) throw new IllegalArgumentException("Source file is a directory"); if (dest.isDirectory()) throw new IllegalArgumentException("Destination file is a directory"); int bufferSize = 4 * 1024; InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); }
11
Code Sample 1: private void copyLocalFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
00
Code Sample 1: public TextureData newTextureData(GLProfile glp, URL url, int internalFormat, int pixelFormat, boolean mipmap, String fileSuffix) throws IOException { InputStream stream = new BufferedInputStream(url.openStream()); try { return newTextureData(glp, stream, internalFormat, pixelFormat, mipmap, fileSuffix); } finally { stream.close(); } } Code Sample 2: public static List<String> unTar(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); TarArchiveInputStream in = new TarArchiveInputStream(inputStream); TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextTarEntry(); } in.close(); return result; }
11
Code Sample 1: public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } }
11
Code Sample 1: FileCacheInputStreamFountain(FileCacheInputStreamFountainFactory factory, InputStream in) throws IOException { file = factory.createFile(); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); in.close(); out.close(); } Code Sample 2: public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(fi)); exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
00
Code Sample 1: private static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String prefix, String suffix) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip, prefix, suffix); } else { if (isFileNameMatch(folder.getName(), prefix, suffix)) { FileInputStream fis = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); IOUtils.copy(fis, zip); fis.close(); } } } Code Sample 2: public void moveMessage(DBMimeMessage oSrcMsg) throws MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.moveMessage()"); DebugFile.incIdent(); } JDCConnection oConn = null; PreparedStatement oStmt = null; ResultSet oRSet = null; BigDecimal oPg = null; BigDecimal oPos = null; int iLen = 0; try { oConn = ((DBStore) getStore()).getConnection(); oStmt = oConn.prepareStatement("SELECT " + DB.pg_message + "," + DB.nu_position + "," + DB.len_mimemsg + " FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, oSrcMsg.getMessageGuid()); oRSet = oStmt.executeQuery(); if (oRSet.next()) { oPg = oRSet.getBigDecimal(1); oPos = oRSet.getBigDecimal(2); iLen = oRSet.getInt(3); } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oConn.setAutoCommit(false); oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "-" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, ((DBFolder) (oSrcMsg.getFolder())).getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oRSet) { try { oRSet.close(); } catch (Exception ignore) { } } if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (null == oPg) throw new MessagingException("Source message not found"); if (null == oPos) throw new MessagingException("Source message position is not valid"); DBFolder oSrcFldr = (DBFolder) oSrcMsg.getFolder(); MboxFile oMboxSrc = null, oMboxThis = null; try { oMboxSrc = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis.appendMessage(oMboxSrc, oPos.longValue(), iLen); oMboxThis.close(); oMboxThis = null; oMboxSrc.purge(new int[] { oPg.intValue() }); oMboxSrc.close(); oMboxSrc = null; } catch (Exception e) { if (oMboxThis != null) { try { oMboxThis.close(); } catch (Exception ignore) { } } if (oMboxSrc != null) { try { oMboxSrc.close(); } catch (Exception ignore) { } } throw new MessagingException(e.getMessage(), e); } try { oConn = ((DBStore) getStore()).getConnection(); BigDecimal dNext = getNextMessage(); String sCatGuid = getCategory().getString(DB.gu_category); oStmt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.gu_category + "=?," + DB.pg_message + "=? WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, sCatGuid); oStmt.setBigDecimal(2, dNext); oStmt.setString(3, oSrcMsg.getMessageGuid()); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.moveMessage()"); } }
00
Code Sample 1: public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } } Code Sample 2: private static MimeType getMimeType(URL url) { String mimeTypeString = null; String charsetFromWebServer = null; String contentType = null; InputStream is = null; MimeType mimeTypeFromWebServer = null; MimeType mimeTypeFromFileSuffix = null; MimeType mimeTypeFromMagicNumbers = null; String fileSufix = null; if (url == null) return null; try { try { is = url.openConnection().getInputStream(); contentType = url.openConnection().getContentType(); } catch (IOException e) { } if (contentType != null) { StringTokenizer st = new StringTokenizer(contentType, ";"); if (st.hasMoreTokens()) mimeTypeString = st.nextToken().toLowerCase(); if (st.hasMoreTokens()) charsetFromWebServer = st.nextToken().toLowerCase(); if (charsetFromWebServer != null) { st = new StringTokenizer(charsetFromWebServer, "="); charsetFromWebServer = null; if (st.hasMoreTokens()) st.nextToken(); if (st.hasMoreTokens()) charsetFromWebServer = st.nextToken().toUpperCase(); } } mimeTypeFromWebServer = mimeString2mimeTypeMap.get(mimeTypeString); fileSufix = getFileSufix(url); mimeTypeFromFileSuffix = getMimeType(fileSufix); mimeTypeFromMagicNumbers = guessTypeUsingMagicNumbers(is, charsetFromWebServer); } finally { IOUtils.closeQuietly(is); } return decideBetweenThreeMimeTypes(mimeTypeFromWebServer, mimeTypeFromFileSuffix, mimeTypeFromMagicNumbers); }
00
Code Sample 1: public static String contents(URL url) throws IOException { InputStream is = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; while (true) { int len = is.read(buf); if (len < 0) { break; } baos.write(buf, 0, len); } is.close(); String contents = new String(baos.toByteArray(), "iso8859_1"); baos.close(); return contents; } Code Sample 2: public List<String> extractUrlList(String url) throws IOException, XPathExpressionException { LinkedList<String> list = new LinkedList<String>(); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); Tidy tidy = new Tidy(); tidy.setErrout(new NullPrintWriter()); Document doc = tidy.parseDOM(conn.getInputStream(), null); int len = conn.getContentLength(); if (len <= 0) len = 32000; ByteArrayOutputStream bout = new ByteArrayOutputStream(len); PrintStream ps = new PrintStream(bout); tidy.pprint(doc, ps); ps.flush(); String content = bout.toString(); Pattern p = Pattern.compile("(http://[\\w\\\\\\./=&?;-]+)"); Matcher m = p.matcher(content); while (m.find()) { list.add(m.group()); } return list; }
11
Code Sample 1: private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); } Code Sample 2: public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
00
Code Sample 1: public String performRequest(TreeMap<String, String> params, boolean isAuthenticated) { params.put("format", "json"); try { URL url = new URL(getApiUrl(params, isAuthenticated)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Reader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; while (reader.ready()) { response += (char) reader.read(); } response = response.replaceFirst("jsonVimeoApi\\(", ""); response = response.substring(0, response.length() - 2); return response; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public static String backupFile(File source) { File backup = new File(source.getParent() + "/~" + source.getName()); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(source))); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(backup))); return FileUtil.backupFile(reader, writer, source.getAbsolutePath()); } catch (FileNotFoundException fe) { String msg = "Failed to find file for backup [" + source.getAbsolutePath() + "]."; _log.error(msg, fe); throw new InvalidImplementationException(msg, fe); } }
00
Code Sample 1: public static String getStringResponse(String urlString) throws Exception { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; StringBuilder buffer = new StringBuilder(); while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } in.close(); return buffer.toString(); } Code Sample 2: private void copyFile(File file, File targetFile) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] tmp = new byte[8192]; int read = -1; while ((read = bis.read(tmp)) > 0) { bos.write(tmp, 0, read); } bis.close(); bos.close(); } catch (Exception e) { if (!targetFile.delete()) { System.err.println("Ups, created copy cant be deleted (" + targetFile.getAbsolutePath() + ")"); } } }
00
Code Sample 1: @SuppressWarnings("static-access") public void run() { while (true) { try { thisThread.sleep(10000); } catch (InterruptedException e) { System.out.print("no connection"); } ++i; umat.flush(); umat = null; try { base = getDocumentBase(); username = getParameter("username"); } catch (Exception e) { } String userdat = "data/" + username + "_l.cod"; URL url = null; try { url = new URL(base, userdat); } catch (MalformedURLException e1) { } InputStream in = null; try { in = url.openStream(); } catch (IOException e1) { } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); } catch (Exception r) { } try { String line = reader.readLine(); StringTokenizer tokenizer = new StringTokenizer(line, " "); int dim = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); this.topol = tokenizer.nextToken().trim().toLowerCase(); xunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); yunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); @SuppressWarnings("unused") String neigh = tokenizer.nextToken().trim().toLowerCase(); String label = null; labels = new String[xunit][yunit]; for (int e = 0; e < yunit; e++) { for (int r = 0; r < xunit; r++) { line = reader.readLine(); StringTokenizer tokenizer2 = new StringTokenizer(line, " "); for (int w = 0; w < dim; w++) { if (tokenizer2.countTokens() > 0) tokenizer2.nextToken(); } while (tokenizer2.countTokens() > 0) { label = tokenizer2.nextToken() + " "; } if (label == null) { labels[r][e] = "none"; } else { labels[r][e] = label; } label = null; } } reader.close(); if (topol.equals("hexa")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { if (q % 2 == 0) { double nenner = (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } if (q % 2 != 0) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } if (topol.equals("rect")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round((nenner / divisor1)); yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } } catch (IOException o) { } String userpng = "images/" + username + ".png"; mt.removeImage(umat); umat = getImage(base, userpng); mt.addImage(umat, 0); try { mt.waitForID(0); } catch (InterruptedException i) { showStatus("Interrupted"); } repaint(); } } Code Sample 2: PathElement(String path) throws MaxError { this.path = path; if (path.startsWith("http:")) { try { url = new URL(path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); valid = (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { valid = false; } } else { if (path.startsWith("jmax:")) file = new File(Registry.resolveJMaxURI(path)); else file = new File(path); valid = file.exists(); } }
00
Code Sample 1: public static String extractIconPath(String siteURL) throws IOException { siteURL = siteURL.trim(); if (!siteURL.startsWith("http://")) { siteURL = "http://" + siteURL; } URL url = new URL(siteURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String iconURL = null; String iconPath = null; String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("type=\"image/x-icon\"") || inputLine.toLowerCase().contains("rel=\"shortcut icon\"")) { String tmp = new String(inputLine); String[] smallLines = inputLine.replace(">", ">\n").split("\n"); for (String smallLine : smallLines) { if (smallLine.contains("type=\"image/x-icon\"") || smallLine.toLowerCase().contains("rel=\"shortcut icon\"")) { tmp = smallLine; break; } } iconURL = tmp.replaceAll("^.*href=\"", ""); iconURL = iconURL.replaceAll("\".*", ""); tmp = null; String originalSiteURL = new String(siteURL); siteURL = getHome(siteURL); if (iconURL.charAt(0) == '/') { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL.substring(1); } else { iconURL = siteURL + iconURL; } } else if (!iconURL.startsWith("http://")) { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } siteURL = originalSiteURL; break; } if (inputLine.contains("</head>".toLowerCase())) { break; } } in.close(); siteURL = getHome(siteURL); if (iconURL == null || "".equals(iconURL.trim())) { iconURL = "favicon.ico"; if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } try { String iconFileName = siteURL; if (iconFileName.startsWith("http://")) { iconFileName = iconFileName.substring(7); } iconFileName = iconFileName.replaceAll("\\W", " ").trim().replace(" ", "_").concat(".ico"); iconPath = JReader.getConfig().getShortcutIconsDir() + File.separator + iconFileName; InputStream inIcon = new URL(iconURL).openStream(); OutputStream outIcon = new FileOutputStream(iconPath); byte[] buf = new byte[1024]; int len; while ((len = inIcon.read(buf)) > 0) { outIcon.write(buf, 0, len); } inIcon.close(); outIcon.close(); } catch (Exception e) { } return iconPath; } Code Sample 2: public static String hashClientPassword(String algorithm, String password, String salt) throws IllegalArgumentException, DruidSafeRuntimeException { if (algorithm == null) { throw new IllegalArgumentException("THE ALGORITHM MUST NOT BE NULL"); } if (password == null) { throw new IllegalArgumentException("THE PASSWORD MUST NOT BE NULL"); } if (salt == null) { salt = ""; } String result = null; try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(password.getBytes()); md.update(salt.getBytes()); result = SecurityHelper.byteArrayToHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new DruidSafeRuntimeException(e); } return result; }
00
Code Sample 1: protected void entryMatched(EntryMonitor monitor, Entry entry) { FTPClient ftpClient = new FTPClient(); try { Resource resource = entry.getResource(); if (!resource.isFile()) { return; } if (server.length() == 0) { return; } String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false); ftpClient.connect(server); if (user.length() > 0) { ftpClient.login(user, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); monitor.handleError("FTP server refused connection:" + server, null); return; } ftpClient.setFileType(FTP.IMAGE_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (directory.length() > 0) { ftpClient.changeWorkingDirectory(directory); } String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate); InputStream is = new BufferedInputStream(monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath()))); boolean ok = ftpClient.storeUniqueFile(filename, is); is.close(); if (ok) { monitor.logInfo("Wrote file:" + directory + " " + filename); } else { monitor.handleError("Failed to write file:" + directory + " " + filename, null); } } catch (Exception exc) { monitor.handleError("Error posting to FTP:" + server, exc); } finally { try { ftpClient.logout(); } catch (Exception exc) { } try { ftpClient.disconnect(); } catch (Exception exc) { } } } Code Sample 2: public static String getServiceContent(String serviceURL) throws IOException { URL url = new URL(serviceURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); byte[] buffer = null; String stringBuffer = ""; buffer = new byte[4096]; int totBytes, bytes, sumBytes = 0; totBytes = connection.getContentLength(); while (true) { bytes = is.read(buffer); if (bytes <= 0) break; stringBuffer = stringBuffer + new String(buffer); } return stringBuffer; } return null; }
11
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } } Code Sample 2: public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; }
00
Code Sample 1: private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; } Code Sample 2: private Bitmap fetchImage(String urlstr) throws Exception { URL url; url = new URL(urlstr); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setDoInput(true); c.setRequestProperty("User-Agent", "Agent"); c.connect(); InputStream is = c.getInputStream(); Bitmap img; img = BitmapFactory.decodeStream(is); return img; }
11
Code Sample 1: void copyFile(File src, File dst) throws IOException { FileInputStream fis = new FileInputStream(src); byte[] buf = new byte[10000]; int n; FileOutputStream fos = new FileOutputStream(dst); while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); copied++; } Code Sample 2: public static File gzipLog() throws IOException { RunnerClass.nfh.flush(); File log = new File(RunnerClass.homedir + "pj.log"); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File(log.getCanonicalPath() + ".pjl"))); FileInputStream in = new FileInputStream(log); int bufferSize = 4 * 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); return new File(log.getCanonicalPath() + ".pjl"); }
00
Code Sample 1: public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; } Code Sample 2: private void initBanner() { for (int k = 0; k < 3; k++) { if (bannerImg == null) { int i = getRandomId(); imageURL = NbBundle.getMessage(BottomContent.class, "URL_BannerImageLink", Integer.toString(i)); bannerURL = NbBundle.getMessage(BottomContent.class, "URL_BannerLink", Integer.toString(i)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(imageURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { bannerImg = new ImageIcon(ImageIO.read(entity.getContent())); EntityUtils.consume(entity); } } catch (IOException ex) { bannerImg = null; } finally { method.abort(); } } else { break; } } if (bannerImg == null) { NotifyUtil.error("Banner Error", "Application could not get banner image. Please check your internet connection.", false); } }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.seriesstatementpanel.getEnteredvalues().get(0).toString().trim().equals("")) { this.showWarningMessage("Enter Series Title"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveSeriesName("2", seriesstatementpanel.getEnteredvalues(), patlib); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SeriesNameServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } } 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 void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) System.out.write(x); } if (args.length == 1) print("Checksum: " + csumi.getChecksum().getValue()); bis.close(); ZipFile zf = new ZipFile("test.zip"); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry) e.nextElement(); print("File: " + ze2); } } Code Sample 2: private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); }
11
Code Sample 1: public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: private ArrayList<String> getFiles(String date) { ArrayList<String> files = new ArrayList<String>(); String info = ""; try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS + date + "/"); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf(".bz2"); if (pos != -1) { token = token.substring(1, pos + 4); files.add(token); } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return files; } Code Sample 2: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); }
11
Code Sample 1: public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); } Code Sample 2: private static String hash(String string) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (Exception e) { return null; } try { md.update(string.getBytes("UTF-8")); } catch (Exception e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
11
Code Sample 1: public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new DocumentListException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); } Code Sample 2: @Override public int updateStatus(UserInfo userInfo, String status, String picturePath) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(SnsConstant.SOHU_UPDATE_STATUS_URL); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("parameter1", "parameterValue1")); parameters.add(new BasicNameValuePair("parameter2", "parameterValue2")); try { post.setEntity(new UrlEncodedFormEntity(parameters)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { HttpResponse response = client.execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; }
00
Code Sample 1: public static int[] sortAscending(double input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] > input[j + 1]) { double mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; } Code Sample 2: public void testJDBCSavepoints() throws Exception { String sql; String msg; int i; PreparedStatement ps; ResultSet rs; Savepoint sp1; Savepoint sp2; Savepoint sp3; Savepoint sp4; Savepoint sp5; Savepoint sp6; Savepoint sp7; int rowcount = 0; sql = "drop table t if exists"; stmt.executeUpdate(sql); sql = "create table t(id int, fn varchar, ln varchar, zip int)"; stmt.executeUpdate(sql); conn1.setAutoCommit(true); conn1.setAutoCommit(false); sql = "insert into t values(?,?,?,?)"; ps = conn1.prepareStatement(sql); ps.setString(2, "Mary"); ps.setString(3, "Peterson-Clancy"); i = 0; for (; i < 10; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp1 = conn1.setSavepoint("savepoint1"); for (; i < 20; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp2 = conn1.setSavepoint("savepoint2"); for (; i < 30; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp3 = conn1.setSavepoint("savepoint3"); for (; i < 40; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp4 = conn1.setSavepoint("savepoint4"); for (; i < 50; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp5 = conn1.setSavepoint("savepoint5"); sp6 = conn1.setSavepoint("savepoint6"); sp7 = conn1.setSavepoint("savepoint7"); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) from t value"; try { assertEquals(msg, 50, rowcount); } catch (Exception e) { } conn2.setAutoCommit(false); conn2.setSavepoint("savepoint1"); conn2.setSavepoint("savepoint2"); msg = "savepoint released succesfully on non-originating connection"; try { conn2.releaseSavepoint(sp2); assertTrue(msg, false); } catch (Exception e) { } try { conn2.rollback(sp1); msg = "succesful rollback to savepoint on " + "non-originating connection"; assertTrue(msg, false); } catch (Exception e) { } msg = "direct execution of <release savepoint> statement failed to " + "release JDBC-created SQL-savepoint with identical savepoint name"; try { conn2.createStatement().executeUpdate("release savepoint \"savepoint2\""); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } msg = "direct execution of <rollback to savepoint> statement failed to " + "roll back to existing JDBC-created SQL-savepoint with identical " + "savepoint name"; try { conn2.createStatement().executeUpdate("rollback to savepoint \"savepoint1\""); } catch (Exception e) { e.printStackTrace(); try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.releaseSavepoint(sp6); msg = "savepoint released succesfully > 1 times"; try { conn1.releaseSavepoint(sp6); assertTrue(msg, false); } catch (Exception e) { } msg = "savepoint released successfully after preceding savepoint released"; try { conn1.releaseSavepoint(sp7); assertTrue(msg, false); } catch (Exception e) { } msg = "preceding same-point savepoint destroyed by following savepoint release"; try { conn1.releaseSavepoint(sp5); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.rollback(sp4); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select * rowcount after 50 inserts - 10 rolled back:"; try { assertEquals(msg, 40, rowcount); } catch (Exception e) { } msg = "savepoint rolled back succesfully > 1 times"; try { conn1.rollback(sp4); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp3); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) after 50 inserts - 20 rolled back:"; try { assertEquals(msg, 30, rowcount); } catch (Exception e) { } msg = "savepoint released succesfully after use in rollback"; try { conn1.releaseSavepoint(sp3); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp1); msg = "savepoint rolled back without raising an exception after " + "rollback to a preceeding savepoint"; try { conn1.rollback(sp2); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(); msg = "savepoint released succesfully when it should have been " + "destroyed by a full rollback"; try { conn1.releaseSavepoint(sp1); assertTrue(msg, false); } catch (Exception e) { } conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.rollback(); conn1.setAutoCommit(false); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); }
00
Code Sample 1: private void alterarCategoria(Categoria cat) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE categoria SET nome_categoria = ? where id_categoria = ?"; ps = conn.prepareStatement(sql); ps.setString(1, cat.getNome()); ps.setInt(2, cat.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: private void downloadTo(URL url, File out) throws IOException { URLConnection conn = url.openConnection(); BufferedInputStream is = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); final int BLOCK_SIZE = 1024; byte[] buf = new byte[BLOCK_SIZE]; int size; while ((size = is.read(buf, 0, BLOCK_SIZE)) > 0) os.write(buf, 0, size); is.close(); os.close(); }
00
Code Sample 1: public static String md5(String plain) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { PApplet.println("[ERROR]: md5() " + e); return ""; } md5.reset(); md5.update(plain.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i += 1) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); } Code Sample 2: public static boolean init(String language) { URL url = S.class.getResource("strings_" + language + ".txt"); strings = new Properties(); try { strings.load(url.openStream()); } catch (Exception e) { String def = "en"; if (language.equals(def)) return false; return init(def); } ; return true; }
00
Code Sample 1: public static String encryption(String oldPass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(oldPass.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } String pass32 = buf.toString(); return pass32; } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } out.setLastModified(in.lastModified()); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.throwing(getClass().getName(), "plainStringToMD5", e); } md.reset(); try { md.update(input.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xF0 & byteHash[i]).charAt(0)); resultString.append(Integer.toHexString(0x0F & byteHash[i])); } return (resultString.toString()); } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
00
Code Sample 1: protected PTask commit_result(Result r, SyrupConnection con) throws Exception { try { int logAction = LogEntry.ENDED; String kk = r.context().task().key(); if (r.in_1_consumed() && r.context().in_1_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, false, null, con); logAction = logAction | LogEntry.IN_1; } if (r.in_2_consumed() && r.context().in_2_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, true, null, con); logAction = logAction | LogEntry.IN_2; } if (r.out_1_result() != null && r.context().out_1_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, false, r.out_1_result(), con); logAction = logAction | LogEntry.OUT_1; } if (r.out_2_result() != null && r.context().out_2_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, true, r.out_2_result(), con); logAction = logAction | LogEntry.OUT_2; } sqlImpl().loggingFunctions().log(r.context().task().key(), logAction, con); boolean isParent = r.context().task().isParent(); if (r instanceof Workflow) { Workflow w = (Workflow) r; Task[] tt = w.tasks(); Link[] ll = w.links(); Hashtable tkeyMap = new Hashtable(); for (int i = 0; i < tt.length; i++) { String key = sqlImpl().creationFunctions().newTask(tt[i], r.context().task(), con); tkeyMap.put(tt[i], key); } for (int j = 0; j < ll.length; j++) { sqlImpl().creationFunctions().newLink(ll[j], tkeyMap, con); } String in_link_1 = sqlImpl().queryFunctions().readInTask(kk, false, con); String in_link_2 = sqlImpl().queryFunctions().readInTask(kk, true, con); String out_link_1 = sqlImpl().queryFunctions().readOutTask(kk, false, con); String out_link_2 = sqlImpl().queryFunctions().readOutTask(kk, true, con); sqlImpl().updateFunctions().rewireInLink(kk, false, w.in_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireInLink(kk, true, w.in_2_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, false, w.out_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, true, w.out_2_binding(), tkeyMap, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateDone(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateDone(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_2, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_2, con); isParent = true; } sqlImpl().updateFunctions().checkAndUpdateDone(kk, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kk, con); PreparedStatement s3 = null; s3 = con.prepareStatementFromCache(sqlImpl().sqlStatements().updateTaskModificationStatement()); java.util.Date dd = new java.util.Date(); s3.setLong(1, dd.getTime()); s3.setBoolean(2, isParent); s3.setString(3, r.context().task().key()); s3.executeUpdate(); sqlImpl().loggingFunctions().log(kk, LogEntry.ENDED, con); con.commit(); return sqlImpl().queryFunctions().readPTask(kk, con); } finally { con.rollback(); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } }
00
Code Sample 1: public String post() { if (content == null || content.equals("")) return "Type something to publish!!"; OutputStreamWriter wr = null; BufferedReader rd = null; try { String data = URLEncoder.encode("api", "UTF-8") + "=" + URLEncoder.encode(apiKey, "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(content, "UTF-8"); data += "&" + URLEncoder.encode("description", "UTF-8") + "=" + URLEncoder.encode(descriptionTextArea.getText() + description_suffix, "UTF-8"); data += "&" + URLEncoder.encode("expiry", "UTF-8") + "=" + URLEncoder.encode((String) expiryComboBox.getSelectedItem(), "UTF-8"); data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode(type, "UTF-8"); data += "&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(nameTextBox.getText(), "UTF-8"); URL url = new URL("http://pastebin.ca/quiet-paste.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; line = rd.readLine(); if (line == null || line.length() < 8 || !line.substring(0, 8).equals("SUCCESS:")) return "Unknown error in publishing the post"; else return "*Publish successful.! The link to your post is.: " + "http://pastebin.ca/" + line.substring(8); } catch (IOException ex) { return "Unable to connect to http://pastebin.ca/\nPlease check your internet connection"; } finally { try { if (wr != null) wr.close(); if (rd != null) rd.close(); } catch (IOException ex) { } } } Code Sample 2: public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); }
11
Code Sample 1: private static void copySmallFile(File sourceFile, File targetFile) throws BusinessException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new BusinessException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'!", e); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LOG.error("Could not close input stream!", e); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LOG.error("Could not close output stream!", e); } } } Code Sample 2: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
11
Code Sample 1: public static void copy(File src, File dest, boolean overwrite) throws IOException { if (!src.exists()) throw new IOException("File source does not exists"); if (dest.exists()) { if (!overwrite) throw new IOException("File destination already exists"); dest.delete(); } else { dest.createNewFile(); } InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dest); byte[] buffer = new byte[1024 * 4]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.close(); is.close(); } Code Sample 2: static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } }
00
Code Sample 1: private String signMethod() { String str = API.SHARED_SECRET; Vector<String> v = new Vector<String>(parameters.keySet()); Collections.sort(v); for (String key : v) { str += key + parameters.get(key); } MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); m.update(str.getBytes(), 0, str.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
00
Code Sample 1: @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); } Code Sample 2: public static void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
00
Code Sample 1: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
11
Code Sample 1: public static String hashPassword(String password) { String passwordHash = ""; try { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); sha1.reset(); sha1.update(password.getBytes()); Base64 encoder = new Base64(); passwordHash = new String(encoder.encode(sha1.digest())); } catch (NoSuchAlgorithmException e) { LoggerFactory.getLogger(UmsAuthenticationProcessingFilter.class.getClass()).error("Failed to generate password hash: " + e.getMessage()); } return passwordHash; } Code Sample 2: 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; } }
00
Code Sample 1: private boolean createPKCReqest(String keystoreLocation, String pw) { boolean created = false; Security.addProvider(new BouncyCastleProvider()); KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when creating PKC request: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when creating PKC request: " + e.getMessage()); } return false; } PKCS10CertificationRequest request = null; PublicKey pk = cert.getPublicKey(); try { request = new PKCS10CertificationRequest("SHA1with" + pk.getAlgorithm(), new X500Principal(((X509Certificate) cert).getSubjectDN().toString()), pk, new DERSet(), (PrivateKey) ks.getKey("saws", pw.toCharArray())); PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(new FileOutputStream("sawsRequest.csr"))); pemWrt.writeObject(request); pemWrt.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error creating PKC request file: " + e.getMessage()); } return false; } return created; } Code Sample 2: public String sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException, NotFoundException { logger.debug(request.getRequestLine().toString()); DefaultHttpClient httpclient = HttpUtil.getNewHttpClient(); configureProxy(httpclient); if (login != null) { final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET))); request.addHeader("Authorization", "Basic: " + credentials); } request.addHeader("Accept-Encoding", "gzip,deflate"); HttpResponse httpResponse = httpclient.execute((HttpUriRequest) request); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server."); } if (responseCode == HttpStatus.SC_FORBIDDEN) { throw new AuthenticationException("Forbidden. Please check the user has proper permissions."); } HttpEntity responseEntity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity); if (responseCode == HttpStatus.SC_NOT_FOUND) { throw new NotFoundException("Server returned '404 not found'. response body:" + responseBody); } if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { List<String> errors = RedmineXMLParser.parseErrors(responseBody); throw new RedmineException(errors); } httpclient.getConnectionManager().shutdown(); return responseBody; }
11
Code Sample 1: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); } Code Sample 2: private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; }
00
Code Sample 1: public static void loginWuploader() throws IOException { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to Wupload"); HttpPost httppost = new HttpPost("http://www.wupload.in/account/login"); httppost.setHeader("Referer", "http://www.wupload.in/"); httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("email", uname)); formparams.add(new BasicNameValuePair("password", pwd)); formparams.add(new BasicNameValuePair("redirect", "/")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("PHPSESSID")) { sessioncookie = "PHPSESSID=" + escookie.getValue(); System.out.println(sessioncookie); } if (escookie.getName().equalsIgnoreCase("email")) { mailcookie = "email=" + escookie.getValue(); login = true; System.out.println(mailcookie); } if (escookie.getName().equalsIgnoreCase("nickname")) { namecookie = "nickname=" + escookie.getValue(); System.out.println(namecookie); } if (escookie.getName().equalsIgnoreCase("isAffiliate")) { affiliatecookie = "isAffiliate=" + escookie.getValue(); System.out.println(affiliatecookie); } if (escookie.getName().equalsIgnoreCase("role")) { rolecookie = "role=" + escookie.getValue(); System.out.println(rolecookie); } } if (login) { System.out.println("Login Success"); getFolderCookies(); } else { System.out.println("Login failed"); } } Code Sample 2: protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } }
00
Code Sample 1: public static String generateMD5(String str) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { logger.log(Level.SEVERE, null, nsae); } return hashword; } Code Sample 2: @SuppressWarnings("unchecked") protected void initializeGraphicalViewer() { GraphicalViewer viewer = getGraphicalViewer(); ScalableRootEditPart rootEditPart = new ScalableRootEditPart(); viewer.setEditPartFactory(new DBEditPartFactory()); 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); List<String> zoomContributions = new ArrayList<String>(); 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)); PrintAction printAction = new PrintAction(this); printAction.setText(DBPlugin.getResourceString("action.print")); printAction.setImageDescriptor(DBPlugin.getImageDescriptor("icons/print.gif")); getActionRegistry().registerAction(printAction); IFile file = ((IFileEditorInput) getEditorInput()).getFile(); RootModel root = null; try { root = VisualDBSerializer.deserialize(file.getContents()); } catch (Exception ex) { DBPlugin.logException(ex); root = new RootModel(); root.setDialectName(DialectProvider.getDialectNames()[0]); } viewer.setContents(root); final DeleteAction deleteAction = new DeleteAction((IWorkbenchPart) this); deleteAction.setSelectionProvider(getGraphicalViewer()); getActionRegistry().registerAction(deleteAction); getGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { deleteAction.update(); } }); MenuManager menuMgr = new MenuManager(); menuMgr.add(new QuickOutlineAction()); menuMgr.add(new Separator()); menuMgr.add(getActionRegistry().getAction(ActionFactory.UNDO.getId())); menuMgr.add(getActionRegistry().getAction(ActionFactory.REDO.getId())); menuMgr.add(new Separator()); PasteAction pasteAction = new PasteAction(this); getActionRegistry().registerAction(pasteAction); getSelectionActions().add(pasteAction.getId()); menuMgr.add(pasteAction); CopyAction copyAction = new CopyAction(this, pasteAction); getActionRegistry().registerAction(copyAction); getSelectionActions().add(copyAction.getId()); menuMgr.add(copyAction); menuMgr.add(getActionRegistry().getAction(ActionFactory.DELETE.getId())); menuMgr.add(new Separator()); menuMgr.add(new AutoLayoutAction(viewer)); menuMgr.add(new DommainEditAction(viewer)); MenuManager convertMenu = new MenuManager(DBPlugin.getResourceString("action.convert")); menuMgr.add(convertMenu); UppercaseAction uppercaseAction = new UppercaseAction(this); convertMenu.add(uppercaseAction); getActionRegistry().registerAction(uppercaseAction); getSelectionActions().add(uppercaseAction.getId()); LowercaseAction lowercaseAction = new LowercaseAction(this); convertMenu.add(lowercaseAction); getActionRegistry().registerAction(lowercaseAction); getSelectionActions().add(lowercaseAction.getId()); Physical2LogicalAction physical2logicalAction = new Physical2LogicalAction(this); convertMenu.add(physical2logicalAction); getActionRegistry().registerAction(physical2logicalAction); getSelectionActions().add(physical2logicalAction.getId()); Logical2PhysicalAction logical2physicalAction = new Logical2PhysicalAction(this); convertMenu.add(logical2physicalAction); getActionRegistry().registerAction(logical2physicalAction); getSelectionActions().add(logical2physicalAction.getId()); menuMgr.add(new ToggleModelAction(viewer)); menuMgr.add(new ChangeDBTypeAction(viewer)); menuMgr.add(new Separator()); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_IN)); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_OUT)); menuMgr.add(new Separator()); menuMgr.add(new CopyAsImageAction(viewer)); menuMgr.add(getActionRegistry().getAction(ActionFactory.PRINT.getId())); menuMgr.add(new Separator()); MenuManager validation = new MenuManager(DBPlugin.getResourceString("action.validation")); validation.add(new ValidateAction(viewer)); validation.add(new DeleteMarkerAction(viewer)); menuMgr.add(validation); MenuManager importMenu = new MenuManager(DBPlugin.getResourceString("action.import")); importMenu.add(new ImportFromJDBCAction(viewer)); importMenu.add(new ImportFromDiagramAction(viewer)); menuMgr.add(importMenu); MenuManager generate = new MenuManager(DBPlugin.getResourceString("action.export")); IGenerator[] generaters = GeneratorProvider.getGeneraters(); for (int i = 0; i < generaters.length; i++) { generate.add(new GenerateAction(generaters[i], viewer, this)); } menuMgr.add(generate); menuMgr.add(new SelectedTablesDDLAction(viewer)); viewer.setContextMenu(menuMgr); viewer.getControl().addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent e) { IStructuredSelection selection = (IStructuredSelection) getGraphicalViewer().getSelection(); Object obj = selection.getFirstElement(); if (obj != null && obj instanceof IDoubleClickSupport) { ((IDoubleClickSupport) obj).doubleClicked(); } } }); outlinePage = new VisualDBOutlinePage(viewer, getEditDomain(), root, getSelectionSynchronizer()); applyPreferences(); viewer.getControl().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.stateMask == SWT.CTRL && e.keyCode == 'o') { new QuickOutlineAction().run(); } } }); }
00
Code Sample 1: private ByteBuffer readProgram(URL url) throws IOException { StringBuilder program = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { program.append(line).append("\n"); } } finally { if (in != null) in.close(); } ByteBuffer buffer = BufferUtils.createByteBuffer(program.length()); for (int i = 0; i < program.length(); i++) { buffer.put((byte) (program.charAt(i) & 0xFF)); } buffer.flip(); return buffer; } Code Sample 2: public MemoryBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
11
Code Sample 1: public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } } Code Sample 2: public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[8192]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
00
Code Sample 1: public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; } Code Sample 2: public void loadFromURLPath(String type, URL urlPath, HashMap parentAttributes) throws IOException { this.urlPath = urlPath; this.type = type; JmeBinaryReader jbr = new JmeBinaryReader(); setProperties(jbr, parentAttributes); InputStream loaderInput = urlPath.openStream(); if (type.equals("xml")) { XMLtoBinary xtb = new XMLtoBinary(); ByteArrayOutputStream BO = new ByteArrayOutputStream(); xtb.sendXMLtoBinary(loaderInput, BO); loaderInput = new ByteArrayInputStream(BO.toByteArray()); } else if (!type.equals("binary")) throw new IOException("Unknown LoaderNode flag: " + type); jbr.loadBinaryFormat(this, loaderInput); }
11
Code Sample 1: private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) { if ((organizationName == null) || (organizationName.equals(""))) { message = "invalid new_organization_name."; return false; } String tmpxml = TextUtil.xmlEscape(organizationName); String tmpdb = DBAccess.SQLEscape(organizationName); if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) { message = "invalid new_organization_name."; return false; } if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) { message = "invalid new_organization_name."; return false; } String[] orgnames = ServerConsoleServlet.getOrganizationNames(); for (int i = 0; i < orgnames.length; i++) { if (orgnames.equals(organizationName)) { message = "already exists."; return false; } } message = "create new organization: " + organizationName; File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName); if (!newOrganizationDirectory.mkdir()) { message = "cannot create directory."; return false; } File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName")); cacheDir.mkdir(); File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName")); confDir.mkdir(); File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName")); rdfDir.mkdir(); File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName")); resourceDir.mkdir(); File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete"); obsoleteDir.mkdir(); File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName")); schemaDir.mkdir(); String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate")); File templ = new File(organization_temp_dir); File[] confFiles = templ.listFiles(); for (int i = 0; i < confFiles.length; i++) { try { FileReader fr = new FileReader(confFiles[i]); FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName()); int c = -1; while ((c = fr.read()) != -1) fw.write(c); fw.flush(); fw.close(); fr.close(); } catch (IOException e) { } } SchemaModelHolder.reloadSchemaModel(organizationName); ResourceModelHolder.reloadResourceModel(organizationName); UserLogServlet.initializeUserLogDB(organizationName); MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username); ResourceModelHolder.reloadResourceModel(organizationName); message = organizationName + " is created. Restart Tomcat to activate this organization."; return true; } Code Sample 2: public byte[] getFile(final String file) throws IOException { if (this.files.contains(file)) { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if ((entry.getName().equals(file)) && (!entry.isDirectory())) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(input, output); output.close(); input.close(); return output.toByteArray(); } } input.close(); } return null; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFile(File src, File dest, boolean notifyUserOnError) { if (src.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } catch (IOException e) { String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } else { String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } }
00
Code Sample 1: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); } Code Sample 2: public void unzip(final File outDir) throws IOException { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if (entry != null) { File file = this.createFile(outDir, entry.getName()); if (!entry.isDirectory()) { FileOutputStream output = new FileOutputStream(file); IOUtils.copy(input, output); output.close(); } } } input.close(); }
11
Code Sample 1: private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; } Code Sample 2: public static final boolean zipUpdate(String zipfile, String name, String oldname, byte[] contents, boolean delete) { try { File temp = File.createTempFile("atf", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(temp)); ZipInputStream zin = new ZipInputStream(in); ZipOutputStream zout = new ZipOutputStream(os); ZipEntry e; ZipEntry e2; byte buffer[] = new byte[TEMP_FILE_BUFFER_SIZE]; int bytesRead; boolean found = false; boolean rename = false; String oname = name; if (oldname != null) { name = oldname; rename = true; } while ((e = zin.getNextEntry()) != null) { if (!e.isDirectory()) { String ename = e.getName(); if (delete && ename.equals(name)) continue; e2 = new ZipEntry(rename ? oname : ename); zout.putNextEntry(e2); if (ename.equals(name)) { found = true; zout.write(contents); } else { while ((bytesRead = zin.read(buffer)) != -1) zout.write(buffer, 0, bytesRead); } zout.closeEntry(); } } if (!found && !delete) { e = new ZipEntry(name); zout.putNextEntry(e); zout.write(contents); zout.closeEntry(); } zin.close(); zout.close(); File fp = new File(zipfile); fp.delete(); MLUtil.copyFile(temp, fp); temp.delete(); return (true); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } return (false); }
00
Code Sample 1: public static Image load(final InputStream input, String format, Point dimension) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); dotOutput.delete(); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); ImageLoader loader = new ImageLoader(); ImageData[] imageData = loader.load(dotOutput.getAbsolutePath()); return new Image(Display.getDefault(), imageData[0]); } } catch (SWTException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); } Code Sample 2: public void run() { try { URL url = new URL("http://mydiversite.appspot.com/version.html"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } } Code Sample 2: public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); }
00
Code Sample 1: public Document parse(Document document) { CSSCompilerBuilder compilerBuilder = new CSSCompilerBuilder(); StyleSheetCompilerFactory compilerFactory = getStyleSheetCompilerFactory(); compilerBuilder.setStyleSheetCompilerFactory(compilerFactory); CSSCompiler cssCompiler = compilerBuilder.getCSSCompiler(); CompiledStyleSheet defaultCompiledStyleSheet; try { URL url = getClass().getResource("/com/volantis/mcs/runtime/default.css"); InputStream stream = url.openStream(); defaultCompiledStyleSheet = cssCompiler.compile(new InputStreamReader(stream), null); } catch (IOException e) { throw new ExtendedRuntimeException(e); } StylingFactory stylingFactory = StylingFactory.getDefaultInstance(); StylingEngine stylingEngine = stylingFactory.createStylingEngine(new InlineStyleSheetCompilerFactory(StylingFunctions.getResolver())); stylingEngine.pushStyleSheet(defaultCompiledStyleSheet); DocumentStyler styler = new DocumentStyler(stylingEngine, XDIMESchemata.CDM_NAMESPACE); styler.style(document); DOMWalker walker = new DOMWalker(new WalkingDOMVisitorStub() { public void visit(Element element) { if (element.getStyles() == null) { throw new IllegalArgumentException("element " + element.getName() + " has no styles"); } } }); walker.walk(document); DOMTransformer transformer = new DeferredInheritTransformer(); document = transformer.transform(null, document); return document; } Code Sample 2: public static boolean download(String address, String localFileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { exception.printStackTrace(); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { return false; } } return true; }
00
Code Sample 1: private String determineGuardedHtml() { StringBuffer buf = new StringBuffer(); if (m_guardedButtonPresent) { buf.append("\n<span id='" + getHtmlIdPrefix() + PUSH_PAGE_SUFFIX + "' style='display:none'>\n"); String location = m_guardedHtmlLocation != null ? m_guardedHtmlLocation : (String) Config.getProperty(Config.PROP_PRESENTATION_DEFAULT_GUARDED_HTML_LOCATION); String html = (String) c_guardedHtmlCache.get(location); if (html == null) { if (log.isDebugEnabled()) log.debug(this.NAME + ".determineGuardedHtml: Reading the Guarded Html Fragment: " + location); URL url = getUrl(location); if (url != null) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf1 = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf1.append(line); buf1.append('\n'); } html = buf1.toString(); } catch (IOException e) { log.warn(this.NAME + ".determineGuardedHtml: Failed to read the Guarded Html Fragment: " + location, e); } finally { try { if (in != null) in.close(); } catch (IOException ex) { log.warn(this.NAME + ".determineGuardedHtml: Failed to close the Guarded Html Fragment: " + location, ex); } } } else { log.warn("Failed to read the Guarded Html Fragment: " + location); } if (html == null) html = "Transaction in Progress"; c_guardedHtmlCache.put(location, html); } buf.append(html); buf.append("\n</span>\n"); } return buf.toString(); } Code Sample 2: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: private void prepareJobFile(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.JOB, zer.getName(), fcopyName)); } Code Sample 2: private static void copy(File source, File target) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
00
Code Sample 1: public static void parseConfigV2(List rootList, InputStream is, javax.servlet.ServletContext context, List configFileList) throws Exception { URL configUrl = CompositePageUtil.class.getResource("/cuttleConfigurationV2.xml"); if (configUrl == null) configUrl = CompositePageUtil.class.getClassLoader().getResource("/cuttleConfigurationV2.xml"); URL dtdUrl = CompositePageUtil.class.getResource("/dtd/cuttleConfiguration.dtd"); if (dtdUrl == null) dtdUrl = CompositePageUtil.class.getClassLoader().getResource("/dtd/cuttleConfiguration.dtd"); Digester digester = DigesterLoader.createDigester(configUrl); digester.setValidating(false); digester.register("-//Cuttle MVC Framework//DTD Cuttle Configuration 1.0//EN", dtdUrl.toString()); XMLCuttleConfiguration cuttleConfiguration = (XMLCuttleConfiguration) digester.parse(is); ConfigureDigester.setXmlCuttleConfiguration(cuttleConfiguration); if (configFileList != null) { for (int i = 0; i < configFileList.size(); i++) { String file = (String) configFileList.get(i); URL url2 = CompositePageUtil.class.getResource(file); if (url2 == null) url2 = CompositePageUtil.class.getClassLoader().getResource(file); if (url2 == null) { logger.error("file path:" + file + " not found!"); } XMLRoot root = (XMLRoot) ConfigureDigester.parseXMLToObject(url2.openStream()); rootList.add(root); } } else { for (int i = 0; i < cuttleConfiguration.getActionConfigs().size(); i++) { XMLActionConfig config = (XMLActionConfig) cuttleConfiguration.getActionConfigs().get(i); URL url2 = context.getResource(config.getResource()); if (url2 == null) { logger.error("file path:" + config.getResource() + " not found!"); } XMLRoot root = (XMLRoot) ConfigureDigester.parseXMLToObject(url2.openStream()); rootList.add(root); } } compositeXMLRoot(rootList); XMLCuttleConfiguration config = ConfigureDigester.getXmlCuttleConfiguration(); if (config != null) { List processUnits = config.getProcessUnits(); if (processUnits != null) { for (int i = 0; i < processUnits.size(); i++) { XMLProcessUnit processUnit = (XMLProcessUnit) processUnits.get(i); if (processUnit.getSpringMapping() == null || processUnit.getSpringMapping().equals("")) { Class businessClass = Class.forName(processUnit.getClazz()); Object business = businessClass.newInstance(); ConfigureDigester.addObjectToPool(business); } } } } } Code Sample 2: public boolean downloadFile(String sourceFilename, String targetFilename) throws RQLException { checkFtpClient(); InputStream in = null; try { in = ftpClient.retrieveFileStream(sourceFilename); if (in == null) { return false; } FileOutputStream target = new FileOutputStream(targetFilename); IOUtils.copy(in, target); in.close(); target.close(); return ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Download of file with name " + sourceFilename + " via FTP from server " + server + " failed.", ex); } }
11
Code Sample 1: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } Code Sample 2: @Override public void incluir(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "insert into cliente select nextval('sq_cliente') as cod_cliente, ? as nome, ? as sexo, ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, cliente.getNome()); stmt.setString(2, cliente.getSexo()); stmt.setInt(3, cliente.getCidade().getCodCidade()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de inserir dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
00
Code Sample 1: public int[] sort() { boolean t = true; int temp = 0; int[] mas = new int[N]; Random rand = new Random(); for (int i = 0; i < N; i++) { mas[i] = rand.nextInt(10) + 1; } while (t) { t = false; for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { temp = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = temp; t = true; } } } return mas; } Code Sample 2: public static Channel getChannelFromXML(String channelURL) throws SAXException, IOException { channel = new Channel(channelURL); downloadedItems = new LinkedList<Item>(); URL url = new URL(channelURL); XMLReader xr = XMLReaderFactory.createXMLReader(); ChannelFactory handler = new ChannelFactory(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(url.openStream())); channel.setUnreadItemsCount(downloadedItems.size()); return channel; }
00
Code Sample 1: private void alterarCategoria(Categoria cat) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE categoria SET nome_categoria = ? where id_categoria = ?"; ps = conn.prepareStatement(sql); ps.setString(1, cat.getNome()); ps.setInt(2, cat.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: public static String move_files(String sessionid, String keys, String absolutePathForTheDestinationTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "move_files"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "move_file")); nameValuePairs.add(new BasicNameValuePair("absolute_new_parent_tag", absolutePathForTheDestinationTag)); nameValuePairs.add(new BasicNameValuePair("keys", keys)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", resultJsonString); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; }
11
Code Sample 1: public static void gunzip() throws Exception { System.out.println("gunzip()"); GZIPInputStream zipin = new GZIPInputStream(new FileInputStream("/zip/myzip.gz")); byte buffer[] = new byte[BLOCKSIZE]; FileOutputStream out = new FileOutputStream("/zip/covers"); for (int length; (length = zipin.read(buffer, 0, BLOCKSIZE)) != -1; ) out.write(buffer, 0, length); out.close(); zipin.close(); } Code Sample 2: public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { LOG.debug("[sgkim] copy - start"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in = null; OutputStream out = null; try { LOG.debug("[sgkim] srcFS: " + srcFS + ", src: " + src); in = srcFS.open(src); LOG.debug("[sgkim] dstFS: " + dstFS + ", dst: " + dst); out = dstFS.create(dst, overwrite); LOG.debug("[sgkim] copyBytes - start"); IOUtils.copyBytes(in, out, conf, true); LOG.debug("[sgkim] copyBytes - end"); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } LOG.debug("[sgkim] copy - end"); if (deleteSource) { return srcFS.delete(src, true); } else { return true; } }
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 FTPClient getFtpClient(TopAnalysisConfig topAnalyzerConfig) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(topAnalyzerConfig.getFtpServer()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new java.lang.RuntimeException("PullFileJobWorker connect ftp error!"); } if (!ftp.login(topAnalyzerConfig.getFtpUserName(), topAnalyzerConfig.getFtpPassWord())) { ftp.logout(); throw new java.lang.RuntimeException("PullFileJobWorker login ftp error!"); } logger.info("Remote system is " + ftp.getSystemName()); ftp.setFileType(FTP.BINARY_FILE_TYPE); if (topAnalyzerConfig.isLocalPassiveMode()) ftp.enterLocalPassiveMode(); return ftp; }
11
Code Sample 1: public String getTags(String content) { StringBuffer xml = new StringBuffer(); OutputStreamWriter osw = null; BufferedReader br = null; try { String reqData = URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(content, "UTF-8"); URL service = new URL(cmdUrl); URLConnection urlConn = service.openConnection(); urlConn.setDoOutput(true); urlConn.connect(); osw = new OutputStreamWriter(urlConn.getOutputStream()); osw.write(reqData); osw.flush(); br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = null; while ((line = br.readLine()) != null) { xml.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (osw != null) { osw.close(); } if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } } return xml.toString(); } Code Sample 2: public static void main(String[] args) { try { URL url = new URL("http://localhost:6557"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); int responseCode = conn.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); conn.disconnect(); } catch (Exception ex) { Logger.getLogger(TestSSLConnection.class.getName()).log(Level.SEVERE, null, ex); } }
11
Code Sample 1: public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
11
Code Sample 1: private static String[] loadDB(String name) throws IOException { URL url = SpecialConstants.class.getResource(name); if (url == null) throw new FileNotFoundException("file " + name + " not found"); InputStream is = url.openStream(); try { InputStreamReader isr = new InputStreamReader(is, "utf8"); BufferedReader br = new BufferedReader(isr); ArrayList<String> entries = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { entries.add(line); } } String[] r = new String[entries.size()]; entries.toArray(r); return r; } finally { is.close(); } } Code Sample 2: public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) startWindow(prop); else if (tag.equals("splitpanel")) startSplitPanel(prop); else if (tag.equals("desktoppane")) startDesktopPane(prop); else if (tag.equals("tabcontrol")) startTabcontrol(prop); else if (tag.equals("panel")) startPanel(prop); else if (tag.equals("statusbar")) startStatusbar(prop); else if (tag.equals("toolbar")) startToolbar(prop); else if (tag.equals("toolbarbutton")) startToolbarbutton(prop); else if (tag.equals("menu")) startMenu(prop); else if (tag.equals("menuitem")) startMenuitem(prop); else if (tag.equals("separator")) menu.addSeparator(); else if (tag.equals("choice")) startChoice(prop); else if (tag.equals("list")) startList(prop); else if (tag.equals("option")) startOption(prop); else if (tag.equals("label")) startLabel(prop); else if (tag.equals("button")) startButton(prop); else if (tag.equals("groupbox")) startGroupbox(prop); else if (tag.equals("radiobutton")) startRadioButton(prop); else if (tag.equals("checkbox")) startCheckbox(prop); else if (tag.equals("image")) startImage(prop); else if (tag.equals("textarea")) startTextArea(prop); else if (tag.equals("singlelineedit")) startSingleLineEdit(prop); else if (tag.equals("treeview")) startTreeview(prop); else if (tag.equals("treeitem")) startTreeitem(prop); else if (tag.equals("table")) startTable(prop); else if (tag.equals("header")) startHeader(prop); else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.addRow(); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("rmbmenuitem")) { if (prop == null) { System.err.println("datawindow.menuitem without properties"); return; } String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); JMenuItem mi = new JMenuItem(label); mi.setActionCommand(action); mi.addActionListener(win); rmbmenu.add(mi); } else if (tag.equals("rmbseparator")) { rmbmenu.addSeparator(); } else if (tag.equals("script")) { win.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; win.script += buffer + "\n"; } r.close(); win.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[win] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
11
Code Sample 1: public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); } Code Sample 2: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { guiBuilder.showError("Copy Error", "IOException during copy", ioe.getMessage()); return false; } }
00
Code Sample 1: private boolean importPKC(String keystoreLocation, String pw, String pkcFile, String alias) { boolean imported = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pkcFile)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); while (bis.available() > 0) { cert = cf.generateCertificate(bis); } } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from file when importing PKC: " + e.getMessage()); } return false; } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(new File(keystoreLocation))); } catch (FileNotFoundException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error accessing key store file when importing certificate: " + e.getMessage()); } return false; } try { if (alias.equals("rootca")) { ks.setCertificateEntry(alias, cert); } else { KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(pw.toCharArray())); ks.setKeyEntry(alias, pkEntry.getPrivateKey(), pw.toCharArray(), new Certificate[] { cert }); } ks.store(bos, pw.toCharArray()); imported = true; } catch (Exception e) { e.printStackTrace(); if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error writing keystore to file when importing key store: " + e.getMessage()); } return false; } return imported; } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
11
Code Sample 1: public boolean refresh() { try { synchronized (text) { stream = (new URL(url)).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } text = sb.toString(); } price = 0; date = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return false; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } Code Sample 2: private void loadServers() { try { URL url = new URL(VirtualDeckConfig.SERVERS_URL); cmbServer.addItem("Local"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; if (in.readLine().equals("[list]")) { while ((str = in.readLine()) != null) { String[] host_line = str.split(";"); Host h = new Host(); h.setIp(host_line[0]); h.setPort(Integer.parseInt(host_line[1])); h.setName(host_line[2]); getServers().add(h); cmbServer.addItem(h.getName()); } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: public InputStream getFileStream(String filePath) { if (this.inJar) { try { URL url = getClassResourceUrl(this.getClass(), filePath); if (url != null) { return url.openStream(); } } catch (IOException ioe) { Debug.signal(Debug.ERROR, this, ioe); } } else { try { return new FileInputStream(filePath); } catch (FileNotFoundException fe) { Debug.signal(Debug.ERROR, this, fe); } } return null; } Code Sample 2: private void zip(FileHolder fileHolder, int zipCompressionLevel) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File zipDestFile = new File(fileHolder.destFiles[0]); try { ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile)); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); ZipEntry entry = new ZipEntry(selectedFile.getName()); outStream.setLevel(zipCompressionLevel); outStream.putNextEntry(entry); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.closeEntry(); this.inStream.close(); } outStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error zipping: " + zipDestFile); logger.logError(errEntry); } return; }
11
Code Sample 1: public static final void parse(String infile, String outfile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(infile)); DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile)); int w = Integer.parseInt(reader.readLine()); int h = Integer.parseInt(reader.readLine()); output.writeByte(w); output.writeByte(h); int lineCount = 2; try { do { for (int i = 0; i < h; i++) { lineCount++; String line = reader.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of file at line " + lineCount); } for (int j = 0; j < w; j++) { char c = line.charAt(j); System.out.print(c); output.writeByte(c); } System.out.println(""); } lineCount++; output.writeShort(Short.parseShort(reader.readLine())); } while (reader.readLine() != null); } finally { reader.close(); output.close(); } } Code Sample 2: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } }
11
Code Sample 1: private static void readIzvestiyaArticles() throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';'); reader.setTrimWhitespace(true); try { while (reader.readRecord()) { String id = reader.get(0); String filename = reader.get(1); StringTokenizer st = new StringTokenizer(filename, "-."); String name = st.nextToken(); String volume = st.nextToken(); String year = st.nextToken(); String extension = st.nextToken(); String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension); id2filename.put(id, filepath); } } finally { reader.close(); } for (Map.Entry<String, String> entry : id2filename.entrySet()) { String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue()); filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX"); if (new File(filepath).exists()) { InputStream in = new FileInputStream(filepath); FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false); try { org.apache.commons.io.IOUtils.copy(in, out); } catch (Exception e) { org.apache.commons.io.IOUtils.closeQuietly(in); org.apache.commons.io.IOUtils.closeQuietly(out); } } else { logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist"); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: private void doOp(String urlString) { URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { e.printStackTrace(); return; } URLConnection conn = null; try { conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode((System.getProperty("fedoragsearch.fgsUserName") + ":" + System.getProperty("fedoragsearch.fgsPassword")).getBytes())); conn.connect(); } catch (IOException e) { e.printStackTrace(); return; } content = null; try { content = conn.getContent(); } catch (IOException e) { e.printStackTrace(); return; } String line; BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content)); try { while ((line = br.readLine()) != null) System.out.println(line); } catch (IOException e1) { e1.printStackTrace(); } } Code Sample 2: private String readRDF() { try { FileReader fileStream = new FileReader(GeoModel.PATH_STORED_FILES + "rdfVersion.xml"); BufferedReader readBuf = new BufferedReader(fileStream); StringBuilder contents = new StringBuilder(); String line; while ((line = readBuf.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } readBuf.close(); return contents.toString(); } catch (IOException e) { MessageViewer.infoMessage(mainFrame, "You are running a demo version using data files fetched from the web.\nResults cannot be saved."); mainFrame.setTitle(mainFrame.getTitle() + ". You are running a demo version using data files fetched from the web. Results cannot be saved."); URL urlRdf; try { urlRdf = new URL(GeoModel.URL_STORED_FILES + "rdfVersion.xml"); URLConnection urlConnRdf = urlRdf.openConnection(); BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlConnRdf.getInputStream())); StringBuilder contents = new StringBuilder(); String line; while ((line = urlReader.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } urlReader.close(); return contents.toString(); } catch (Exception e1) { return null; } } }
00
Code Sample 1: public static void executeUpdate(Database db, String... statements) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(db); con.setAutoCommit(false); stmt = con.createStatement(); for (String statement : statements) { stmt.executeUpdate(statement); } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } throw e; } finally { closeStatement(stmt); closeConnection(con); } } Code Sample 2: private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException { URL wsdlurl = null; try { wsdlurl = new URL(uri); } catch (MalformedURLException e) { return new InputSource(uri); } if (username == null && wsdlurl.getUserInfo() == null) { return new InputSource(uri); } if (!wsdlurl.getProtocol().startsWith("http")) { return new InputSource(uri); } URLConnection connection = wsdlurl.openConnection(); if (!(connection instanceof HttpURLConnection)) { return new InputSource(uri); } HttpURLConnection uconn = (HttpURLConnection) connection; String userinfo = wsdlurl.getUserInfo(); uconn.setRequestMethod("GET"); uconn.setAllowUserInteraction(false); uconn.setDefaultUseCaches(false); uconn.setDoInput(true); uconn.setDoOutput(false); uconn.setInstanceFollowRedirects(true); uconn.setUseCaches(false); String auth = null; if (userinfo != null) { auth = userinfo; } else if (username != null) { auth = (password == null) ? username : username + ":" + password; } if (auth != null) { uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); }
00
Code Sample 1: public static byte[] expandPasswordToKey(String password, int keyLen, byte[] salt) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] mdBuf = new byte[digLen]; byte[] key = new byte[keyLen]; int cnt = 0; while (cnt < keyLen) { if (cnt > 0) { md5.update(mdBuf); } md5.update(password.getBytes()); md5.update(salt); md5.digest(mdBuf, 0, digLen); int n = ((digLen > (keyLen - cnt)) ? keyLen - cnt : digLen); System.arraycopy(mdBuf, 0, key, cnt, n); cnt += n; } return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKey: " + e); } } Code Sample 2: public static AudioInputStream getWavFromURL(String urlstr) { URL url; AudioInputStream ais = null; try { url = new URL(urlstr); URLConnection c = url.openConnection(); c.connect(); InputStream stream = c.getInputStream(); ais = new AudioInputStream(stream, playFormat, AudioSystem.NOT_SPECIFIED); LOG.debug("[getWavFromURL]Getting audio from URL: {}", url); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ais; }
11
Code Sample 1: private static List<CountryEntry> retrieveCountries() throws IOException { URL url = new URL("http://" + ISO_3166_HOST + ISO_3166_TXT_FILE_PATH); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); List<CountryEntry> countries = new LinkedList<CountryEntry>(); boolean parsing = false; int trCount = 0; int tdCount = 0; CountryEntry current = new CountryEntry(); String nextLine = input.readLine(); while (nextLine != null) { if (nextLine.startsWith("<table")) { parsing = true; } if (nextLine.startsWith("</table>")) { break; } if (parsing) { if (nextLine.startsWith("<tr")) { trCount++; } else { if ((trCount > 1 && nextLine.startsWith("<td"))) { tdCount++; String data = pullData(nextLine); switch(tdCount) { case 1: current.setName(getCountryName(data)); break; case 2: current.setNumber(data); break; case 3: current.setAlpha3(data); break; case 4: current.setAlpha2(data); break; case 5: countries.add(current); current = new CountryEntry(); tdCount = 0; break; default: String msg = "Parsing error. Unexpected column: [" + data + "]"; throw new IllegalStateException(msg); } } } } nextLine = input.readLine(); } input.close(); return countries; } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestPath = req.getRequestURI(); String cdecUrl = "http://cdec.water.ca.gov" + requestPath + "?" + req.getQueryString(); System.out.println("CDEC URL: " + cdecUrl); URL url = new URL(cdecUrl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); String line = null; int ncolumnInner = 0; while ((line = reader.readLine()) != null) { if (line.contains("<div class=\"column_inner\"")) { ncolumnInner++; } if (ncolumnInner == 2) { if (line.contains("</div>")) { break; } if (line.contains("href")) { line = line.replaceAll("href", " target=\"external_page\" href"); } if (line.contains("http://cdec.water.ca.gov:80")) { line = line.replaceAll("http://cdec.water.ca.gov:80/", "/"); } if (line.contains("href=")) { line = line.replaceAll("(href=\"|href=)", "$1http://cdec.water.ca.gov"); } buffer.append(line); } else { continue; } } resp.getWriter().write(buffer.toString()); resp.getWriter().flush(); reader.close(); }
00
Code Sample 1: public void actualizar() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ms = null; if (!validado) { validado = validar(); } if (!validado) { throw new Exception("No s'ha realitzat la validació de les dades del registre "); } registroActualizado = false; try { int fzaanoe; String campo; fechaTest = dateF.parse(datasalida); Calendar cal = Calendar.getInstance(); cal.setTime(fechaTest); DateFormat date1 = new SimpleDateFormat("yyyyMMdd"); fzaanoe = Integer.parseInt(anoSalida); int fzafent = Integer.parseInt(date1.format(fechaTest)); conn = ToolsBD.getConn(); conn.setAutoCommit(false); int fzanume = Integer.parseInt(numeroSalida); int fzacagc = Integer.parseInt(oficina); int off_codi = 0; try { off_codi = Integer.parseInt(oficinafisica); } catch (Exception e) { } fechaTest = dateF.parse(data); cal.setTime(fechaTest); int fzafdoc = Integer.parseInt(date1.format(fechaTest)); String fzacone, fzacone2; if (idioex.equals("1")) { fzacone = comentario; fzacone2 = ""; } else { fzacone = ""; fzacone2 = comentario; } String fzaproce; int fzactagg, fzacagge; if (fora.equals("")) { fzactagg = 90; fzacagge = Integer.parseInt(balears); fzaproce = ""; } else { fzaproce = fora; fzactagg = 0; fzacagge = 0; } int ceros = 0; int fzacorg = Integer.parseInt(remitent); int fzanent; String fzacent; if (altres.equals("")) { altres = ""; fzanent = Integer.parseInt(entidad2); fzacent = entidadCastellano; } else { fzanent = 0; fzacent = ""; } int fzacidi = Integer.parseInt(idioex); horaTest = horaF.parse(hora); cal.setTime(horaTest); DateFormat hhmm = new SimpleDateFormat("HHmm"); int fzahora = Integer.parseInt(hhmm.format(horaTest)); if (entrada1.equals("")) { entrada1 = "0"; } if (entrada2.equals("")) { entrada2 = "0"; } int fzanloc = Integer.parseInt(entrada1); int fzaaloc = Integer.parseInt(entrada2); if (disquet.equals("")) { disquet = "0"; } int fzandis = Integer.parseInt(disquet); if (fzandis > 0) { ToolsBD.actualizaDisqueteEntrada(conn, fzandis, oficina, anoSalida, errores); } Date fechaSystem = new Date(); DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd"); int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem)); DateFormat hhmmss = new SimpleDateFormat("HHmmss"); DateFormat sss = new SimpleDateFormat("S"); String ss = sss.format(fechaSystem); if (ss.length() > 2) { ss = ss.substring(0, 2); } int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss); if (correo != null) { String insertBZNCORR = "INSERT INTO BZNCORR (FZPCENSA, FZPCAGCO, FZPANOEN, FZPNUMEN, FZPNCORR)" + "VALUES (?,?,?,?,?)"; String updateBZNCORR = "UPDATE BZNCORR SET FZPNCORR=? WHERE FZPCENSA=? AND FZPCAGCO=? AND FZPANOEN=? AND FZPNUMEN=?"; String deleteBZNCORR = "DELETE FROM BZNCORR WHERE FZPCENSA=? AND FZPCAGCO=? AND FZPANOEN=? AND FZPNUMEN=?"; int actualizados = 0; if (!correo.trim().equals("")) { ms = conn.prepareStatement(updateBZNCORR); ms.setString(1, correo); ms.setString(2, "S"); ms.setInt(3, fzacagc); ms.setInt(4, fzaanoe); ms.setInt(5, fzanume); actualizados = ms.executeUpdate(); ms.close(); if (actualizados == 0) { ms = conn.prepareStatement(insertBZNCORR); ms.setString(1, "S"); ms.setInt(2, fzacagc); ms.setInt(3, fzaanoe); ms.setInt(4, fzanume); ms.setString(5, correo); ms.execute(); ms.close(); } } else { ms = conn.prepareStatement(deleteBZNCORR); ms.setString(1, "S"); ms.setInt(2, fzacagc); ms.setInt(3, fzaanoe); ms.setInt(4, fzanume); ms.execute(); } } String deleteOfifis = "DELETE FROM BZSALOFF WHERE FOSANOEN=? AND FOSNUMEN=? AND FOSCAGCO=?"; ms = conn.prepareStatement(deleteOfifis); ms.setInt(1, fzaanoe); ms.setInt(2, fzanume); ms.setInt(3, fzacagc); ms.execute(); ms.close(); String insertOfifis = "INSERT INTO BZSALOFF (FOSANOEN, FOSNUMEN, FOSCAGCO, OFS_CODI)" + "VALUES (?,?,?,?)"; ms = conn.prepareStatement(insertOfifis); ms.setInt(1, fzaanoe); ms.setInt(2, fzanume); ms.setInt(3, fzacagc); ms.setInt(4, off_codi); ms.execute(); ms.close(); ms = conn.prepareStatement("UPDATE BZSALIDA SET FZSFDOCU=?, FZSREMIT=?, FZSCONEN=?, FZSCTIPE=?, " + "FZSCEDIE=?, FZSENULA=?, FZSPROCE=?, FZSFENTR=?, FZSCTAGG=?, FZSCAGGE=?, FZSCORGA=?, " + "FZSCENTI=?, FZSNENTI=?, FZSHORA=?, FZSCIDIO=?, FZSCONE2=?, FZSNLOC=?, FZSALOC=?, FZSNDIS=?, " + "FZSCUSU=?, FZSCIDI=? WHERE FZSANOEN=? AND FZSNUMEN=? AND FZSCAGCO=? "); ms.setInt(1, fzafdoc); ms.setString(2, (altres.length() > 30) ? altres.substring(0, 30) : altres); ms.setString(3, (fzacone.length() > 160) ? fzacone.substring(0, 160) : fzacone); ms.setString(4, (tipo.length() > 2) ? tipo.substring(0, 1) : tipo); ms.setString(5, "N"); ms.setString(6, (registroAnulado.length() > 1) ? registroAnulado.substring(0, 1) : registroAnulado); ms.setString(7, (fzaproce.length() > 25) ? fzaproce.substring(0, 25) : fzaproce); ms.setInt(8, fzafent); ms.setInt(9, fzactagg); ms.setInt(10, fzacagge); ms.setInt(11, fzacorg); ms.setString(12, (fzacent.length() > 7) ? fzacent.substring(0, 8) : fzacent); ms.setInt(13, fzanent); ms.setInt(14, fzahora); ms.setInt(15, fzacidi); ms.setString(16, (fzacone2.length() > 160) ? fzacone2.substring(0, 160) : fzacone2); ms.setInt(17, fzanloc); ms.setInt(18, fzaaloc); ms.setInt(19, fzandis); ms.setString(20, (usuario.toUpperCase().length() > 10) ? usuario.toUpperCase().substring(0, 10) : usuario.toUpperCase()); ms.setString(21, idioma); ms.setInt(22, fzaanoe); ms.setInt(23, fzanume); ms.setInt(24, fzacagc); boolean modificado = false; if (!motivo.equals("")) { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.RegistroModificadoSalidaHome"); RegistroModificadoSalidaHome home = (RegistroModificadoSalidaHome) javax.rmi.PortableRemoteObject.narrow(ref, RegistroModificadoSalidaHome.class); RegistroModificadoSalida registroModificado = home.create(); registroModificado.setAnoSalida(fzaanoe); registroModificado.setOficina(fzacagc); if (!entidad1Nuevo.trim().equals("")) { if (entidad2Nuevo.equals("")) { entidad2Nuevo = "0"; } } int fzanentNuevo; String fzacentNuevo; if (altresNuevo.trim().equals("")) { altresNuevo = ""; fzanentNuevo = Integer.parseInt(entidad2Nuevo); fzacentNuevo = convierteEntidadCastellano(entidad1Nuevo, conn); } else { fzanentNuevo = 0; fzacentNuevo = ""; } if (!fzacentNuevo.equals(fzacent) || fzanentNuevo != fzanent) { registroModificado.setEntidad2(fzanentNuevo); registroModificado.setEntidad1(fzacentNuevo); } else { registroModificado.setEntidad2(0); registroModificado.setEntidad1(""); } if (!comentarioNuevo.trim().equals(comentario.trim())) { registroModificado.setExtracto(comentarioNuevo); } else { registroModificado.setExtracto(""); } registroModificado.setUsuarioModificacion(usuario.toUpperCase()); registroModificado.setNumeroRegistro(fzanume); if (altresNuevo.equals(altres)) { registroModificado.setRemitente(""); } else { registroModificado.setRemitente(altresNuevo); } registroModificado.setMotivo(motivo); modificado = registroModificado.generarModificacion(conn); registroModificado.remove(); } if ((modificado && !motivo.equals("")) || motivo.equals("")) { int afectados = ms.executeUpdate(); if (afectados > 0) { registroActualizado = true; } else { registroActualizado = false; } String remitente = ""; if (!altres.trim().equals("")) { remitente = altres; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); remitente = valor.recuperaRemitenteCastellano(fzacent, fzanent + ""); valor.remove(); } try { Class t = Class.forName("es.caib.regweb.module.PluginHook"); Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class }; Object[] params = { "M", new Integer(fzaanoe), new Integer(fzanume), new Integer(fzacagc), new Integer(fzafdoc), remitente, comentario, tipo, new Integer(fzafent), new Integer(fzacagge), fzaproce, new Integer(fzacorg), idioma }; java.lang.reflect.Method metodo = t.getMethod("salida", partypes); metodo.invoke(null, params); } catch (IllegalAccessException iae) { } catch (IllegalArgumentException iae) { } catch (InvocationTargetException ite) { } catch (NullPointerException npe) { } catch (ExceptionInInitializerError eiie) { } catch (NoSuchMethodException nsme) { } catch (SecurityException se) { } catch (LinkageError le) { } catch (ClassNotFoundException le) { } String Stringsss = sss.format(fechaSystem); switch(Stringsss.length()) { case (1): Stringsss = "00" + Stringsss; break; case (2): Stringsss = "0" + Stringsss; break; } int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss); logLopdBZSALIDA("UPDATE", (usuario.toUpperCase().length() > 10) ? usuario.toUpperCase().substring(0, 10) : usuario.toUpperCase(), fzahsis, horamili, fzanume, fzaanoe, fzacagc); conn.commit(); } else { registroActualizado = false; errores.put("", "Error inesperat, no s'ha modificat el registre"); throw new RemoteException("Error inesperat, no s'ha modifcat el registre"); } } catch (Exception ex) { System.out.println("Error inesperat " + ex.getMessage()); ex.printStackTrace(); registroActualizado = false; errores.put("", "Error inesperat, no s'ha modificat el registre" + ": " + ex.getClass() + "->" + ex.getMessage()); try { if (conn != null) conn.rollback(); } catch (SQLException sqle) { throw new RemoteException("S'ha produ\357t un error i no s'han pogut tornar enrere els canvis efectuats", sqle); } throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex); } finally { ToolsBD.closeConn(conn, ms, null); } } Code Sample 2: private StringBuffer hashPassword(StringBuffer password, String mode) { MessageDigest m = null; StringBuffer hash = new StringBuffer(); try { m = MessageDigest.getInstance(mode); m.update(password.toString().getBytes("UTF8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] digest = m.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); hash.append(hex); } return hash; }
00
Code Sample 1: public final InputStream getStreamFromUrl(final URL url) { try { if (listener != null) { listener.openedStream(url); } return url.openStream(); } catch (IOException e) { listener.exceptionThrown(e); return null; } } Code Sample 2: private static void initialize() throws IOException { System.out.println("Getting startup cookies from localhostr.com"); HttpGet httpget = new HttpGet("http://localhostr.com/"); if (login) { httpget.setHeader("Cookie", sessioncookie); } HttpResponse myresponse = httpclient.execute(httpget); HttpEntity myresEntity = myresponse.getEntity(); localhostrurl = EntityUtils.toString(myresEntity); localhostrurl = parseResponse(localhostrurl, "url : '", "'"); System.out.println("Localhost url : " + localhostrurl); InputStream is = myresponse.getEntity().getContent(); is.close(); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void copy(File src, File dest) throws FileNotFoundException, IOException { FileInputStream srcStream = new FileInputStream(src); FileOutputStream destStream = new FileOutputStream(dest); FileChannel srcChannel = srcStream.getChannel(); FileChannel destChannel = destStream.getChannel(); srcChannel.transferTo(0, srcChannel.size(), destChannel); destChannel.close(); srcChannel.close(); destStream.close(); srcStream.close(); }
11
Code Sample 1: @Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } } Code Sample 2: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }