label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; } 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 String fetchContent() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { buf.append(str); } return buf.toString(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public static void addImageDB(String pictogramsPath, String pictogramToAddPath, String language, String type, String word) { try { Class.forName("org.sqlite.JDBC"); String fileName = pictogramsPath + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { int idL = 0, idT = 0; G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select id from language where name=\"" + language + "\""); while (rs.next()) { idL = rs.getInt("id"); } rs.close(); stat.close(); stat = G.conn.createStatement(); rs = stat.executeQuery("select id from type where name=\"" + type + "\""); while (rs.next()) { idT = rs.getInt("id"); } rs.close(); stat.close(); String id = pictogramToAddPath.substring(pictogramToAddPath.lastIndexOf(File.separator) + 1, pictogramToAddPath.length()); String idOrig = id; String pathSrc = pictogramToAddPath; String pathDst = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, word.toLowerCase()); stmt.setInt(2, idL); stmt.setInt(3, idT); stmt.setString(4, id); stmt.setString(5, idOrig); stmt.executeUpdate(); stmt.close(); G.conn.close(); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: @Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public void copyServer(int id) throws Exception { File in = new File("servers" + File.separatorChar + "server_" + id); File serversDir = new File("servers" + File.separatorChar); int newNumber = serversDir.listFiles().length + 1; System.out.println("New File Number: " + newNumber); File out = new File("servers" + File.separatorChar + "server_" + newNumber); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { e.printStackTrace(); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } getServer(newNumber - 1); }
00
Code Sample 1: public Item findById(String itemId) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); FindItemByIdRequest request = new FindItemByIdRequest(); request.setItemID(itemId); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("FindItemByIdRequest", FindItemByIdRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("FindItemByIdResponse", FindItemByIdResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/findItemById?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); FindItemByIdResponse fibiResponse = (FindItemByIdResponse) reader.fromXML(result); return fibiResponse.getItem(); } return null; } Code Sample 2: private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
11
Code Sample 1: private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); System.exit(1); } return null; } Code Sample 2: private String md5Digest(String plain) throws Exception { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(plain.trim().getBytes()); byte pwdDigest[] = digest.digest(); StringBuilder md5buffer = new StringBuilder(); for (int i = 0; i < pwdDigest.length; i++) { int number = 0xFF & pwdDigest[i]; if (number <= 0xF) { md5buffer.append('0'); } md5buffer.append(Integer.toHexString(number)); } return md5buffer.toString(); }
00
Code Sample 1: public static String digestMd5(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("文字列がNull、または空です。"); } MessageDigest md5; byte[] enclyptedHash; try { md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); enclyptedHash = md5.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ""; } return bytesToHexString(enclyptedHash); } Code Sample 2: public void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } Code Sample 2: public static boolean copyFile(final File src, final File dst) throws FileNotFoundException { if (src == null || dst == null || src.equals(dst)) { return false; } boolean result = false; if (src.exists()) { if (dst.exists() && !dst.canWrite()) { return false; } final FileInputStream srcStream = new FileInputStream(src); final FileOutputStream dstStream = new FileOutputStream(dst); final FileChannel srcChannel = srcStream.getChannel(); final FileChannel dstChannel = dstStream.getChannel(); FileLock dstLock = null; FileLock srcLock = null; try { srcLock = srcChannel.tryLock(0, Long.MAX_VALUE, true); dstLock = dstChannel.tryLock(); if (srcLock != null && dstLock != null) { int maxCount = 64 * 1024 * 1024 - 32 * 1024; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, maxCount, dstChannel); } } } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } finally { if (srcChannel != null) { try { if (srcLock != null) { srcLock.release(); } srcChannel.close(); srcStream.close(); } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } if (dstChannel != null) { try { if (dstLock != null) { dstLock.release(); } dstChannel.close(); dstStream.close(); result = true; } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } } } return result; }
11
Code Sample 1: private boolean getCached(Get g) throws IOException { boolean ret = false; File f = getCachedFile(g); if (f.exists()) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(f); os = new FileOutputStream(getDestFile(g)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public void copiarMidias(final File vidDir, final File imgDir) { for (int i = 0; i < getMidias().size(); i++) { try { FileChannel src = new FileInputStream(getMidias().get(i).getUrl().trim()).getChannel(); FileChannel dest; if (getMidias().get(i).getTipo().equals("video")) { FileChannel vidDest = new FileOutputStream(vidDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = vidDest; } else { FileChannel midDest = new FileOutputStream(imgDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = midDest; } dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (Exception e) { System.err.print(e.getMessage()); 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(); } }
11
Code Sample 1: public boolean limpiarContrincantexRonda(jugadorxDivxRonda unjxdxr) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = 0 " + " WHERE idJugxDivxRnd = " + unjxdxr.getIdJugxDivxRnd(); try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public static boolean insereCapitulo(final Connection con, Capitulo cap, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodCapitulo(con, cap); String text = desc.getTexto().replaceAll("[']", "\""); String titulo = cap.getTitulo().replaceAll("['\"]", ""); String coment = cap.getComentario().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + text + "')"); smt.executeUpdate("INSERT INTO capitulo VALUES(" + cap.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO cap_aut VALUES(" + cap.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "CAPITULO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
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: void copyFileAscii(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { System.err.println(ex.toString()); } }
11
Code Sample 1: private static String md5(String digest, String data) throws IOException { MessageDigest messagedigest; try { messagedigest = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } messagedigest.update(data.getBytes("ISO-8859-1")); byte[] bytes = messagedigest.digest(); StringBuilder stringbuffer = new StringBuilder(bytes.length * 2); for (int j = 0; j < bytes.length; j++) { int k = bytes[j] >>> 4 & 0x0f; stringbuffer.append(hexChars[k]); k = bytes[j] & 0x0f; stringbuffer.append(hexChars[k]); } return stringbuffer.toString(); } Code Sample 2: @Override protected Object transform(Row inputs) throws FunctionException { StringBuffer buffer = new StringBuffer(); for (IColumn c : inputs.getColumns()) { buffer.append(c.getValueAsString() + "|"); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(buffer.toString().getBytes()); byte[] hash = digest.digest(); return getHex(hash); } catch (Exception e) { throw new FunctionException(e); } }
00
Code Sample 1: public static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString) throws IOException { dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false); if (!srcFS.getFileStatus(srcDir).isDir()) return false; OutputStream out = dstFS.create(dstFile); try { FileStatus contents[] = srcFS.listStatus(srcDir); for (int i = 0; i < contents.length; i++) { if (!contents[i].isDir()) { InputStream in = srcFS.open(contents[i].getPath()); try { IOUtils.copyBytes(in, out, conf, false); if (addString != null) out.write(addString.getBytes("UTF-8")); } finally { in.close(); } } } } finally { out.close(); } if (deleteSource) { return srcFS.delete(srcDir, true); } else { return true; } } Code Sample 2: public static String exchangeForSessionToken(String protocol, String domain, String onetimeUseToken, PrivateKey key) throws IOException, GeneralSecurityException, AuthenticationException { String sessionUrl = getSessionTokenUrl(protocol, domain); URL url = new URL(sessionUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); String header = formAuthorizationHeader(onetimeUseToken, key, url, "GET"); httpConn.setRequestProperty("Authorization", header); if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AuthenticationException(httpConn.getResponseCode() + ": " + httpConn.getResponseMessage()); } String body = IOUtils.toString(httpConn.getInputStream()); Map parsedTokens = StringUtils.string2Map(body, "\n", "=", true); parsedTokens = StringUtils.lowercaseKeys(parsedTokens); return (String) parsedTokens.get("token"); }
11
Code Sample 1: @SuppressWarnings(value = "RetentionPolicy.SOURCE") public static byte[] getHashMD5(String chave) { byte[] hashMd5 = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(chave.getBytes()); hashMd5 = md.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); Dialog.erro(ex.getMessage(), null); } return (hashMd5); } Code Sample 2: public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
00
Code Sample 1: public void testRelativeRedirect2() throws Exception { int port = this.localServer.getServicePort(); String host = this.localServer.getServiceHostName(); this.localServer.register("*", new RelativeRedirectService2()); DefaultHttpClient client = new DefaultHttpClient(); HttpContext context = new BasicHttpContext(); client.getParams().setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, false); HttpGet httpget = new HttpGet("/test/oldlocation"); HttpResponse response = client.execute(getServerHttp(), httpget, context); HttpEntity e = response.getEntity(); if (e != null) { e.consumeContent(); } HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); assertEquals("/test/relativelocation", reqWrapper.getRequestLine().getUri()); assertEquals(host, targetHost.getHostName()); assertEquals(port, targetHost.getPort()); } Code Sample 2: public boolean pollLocation(int device) { if (device < numDevices) { try { HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); JSONObject object = (JSONObject) JSONValue.parse(reader); JSONArray array = ((JSONArray) object.get("content")); object = (JSONObject) array.get(device); IPhoneLocation iPhoneLocation = getLocation(object); if (iPhoneLocation != null) { iPhoneRouteList.get(device).addLocation(iPhoneLocation); } } catch (ClientProtocolException ex) { logger.log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return false; } } else { logger.log(Level.WARNING, "Device {0} is out of range ({1} max)", new Object[] { (device + 1), numDevices }); return false; } return true; }
11
Code Sample 1: protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } } Code Sample 2: @Override public void run() { try { IOUtils.copy(_is, processOutStr); } catch (final IOException ioe) { proc.destroy(); } finally { IOUtils.closeQuietly(_is); IOUtils.closeQuietly(processOutStr); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copyFile(IPath fromFileName, IPath toFileName) throws IOException { File fromFile = fromFileName.toFile(); File toFile = toFileName.toFile(); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } InputStream from = null; OutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(fromFile)); to = new BufferedOutputStream(new FileOutputStream(toFile)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
11
Code Sample 1: @Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; } Code Sample 2: public BufferedImage process(final InputStream is, DjatokaDecodeParam params) throws DjatokaException { if (isWindows) return processUsingTemp(is, params); ArrayList<Double> dims = null; if (params.getRegion() != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyStream(is, baos); dims = getRegionMetadata(new ByteArrayInputStream(baos.toByteArray()), params); return process(new ByteArrayInputStream(baos.toByteArray()), dims, params); } else return process(is, dims, params); }
00
Code Sample 1: public static void addProviders(URL url) { Reader reader = null; Properties prop = new Properties(); try { reader = new InputStreamReader(url.openStream()); prop.load(reader); } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } for (Map.Entry<Object, Object> entry : prop.entrySet()) { try { Class<?> cla = Class.forName((String) entry.getValue(), true, Thread.currentThread().getContextClassLoader()); providers.put(((String) entry.getKey()).toUpperCase(), (CharsetProvider) cla.newInstance()); } catch (Throwable t) { } } } Code Sample 2: protected boolean downloadFile(TestThread thread, ActionResult result) { result.setRequestString("download file " + remoteFile); InputStream input = null; OutputStream output = null; OutputStream target = null; boolean status = false; ftpClient.enterLocalPassiveMode(); try { if (localFile != null) { File lcFile = new File(localFile); if (lcFile.exists() && lcFile.isDirectory()) output = new FileOutputStream(new File(lcFile, remoteFile)); else output = new FileOutputStream(lcFile); target = output; } else { target = new FileOutputStream(remoteFile); } input = ftpClient.retrieveFileStream(remoteFile); long bytes = IOUtils.copy(input, target); status = bytes > 0; if (status) { result.setResponseLength(bytes); } } catch (Exception e) { result.setException(new TestActionException(config, e)); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return status; }
00
Code Sample 1: @Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } Code Sample 2: public static ArrayList search(String query) throws Exception { ArrayList list = new ArrayList(); String url = "http://hypem.com/playlist/search/" + query + "/xml/1/list.xspf"; HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); XmlNode node = XmlLoader.load(conn.getInputStream()); XmlNode tracks[] = node.getFirstChild("trackList").getChild("track"); for (int i = 0; i < tracks.length; i++) { String location = decrypt(tracks[i].getFirstChild("location").getText()); String annotation = tracks[i].getFirstChild("annotation").getText().replaceAll("[\r\n]", ""); list.add(location); System.out.print("found in Hypem: "); System.out.print(annotation); System.out.print(", "); System.out.println(location); } return list; }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } } Code Sample 2: public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } }
00
Code Sample 1: public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception { URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid()); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; boolean chargerLyrics = false; StringBuffer sb = new StringBuffer(""); String lyrics = null; while ((ligne = br.readLine()) != null) { log.debug("==> " + ligne); if (chargerLyrics && ligne.indexOf("<center>") != -1) { break; } if (chargerLyrics) { sb.append(ligne.trim()); } if (!chargerLyrics && ligne.indexOf("<center>") != -1) { chargerLyrics = true; } } lyrics = sb.toString(); lyrics = lyrics.replaceAll("<br>", "\n").trim(); log.debug("Parole : " + lyrics); tb.setLyrics(lyrics); br.close(); httpStream.close(); } Code Sample 2: public static Document getDocument(URL url, boolean validate) throws QTIParseException { try { return getDocument(new InputSource(url.openStream()), validate, null); } catch (IOException ex) { throw new QTIParseException(ex); } }
11
Code Sample 1: protected void unZip() throws PersistenceException { boolean newZip = false; try { if (null == backup) { mode = (String) context.get(Context.MODE); if (null == mode) mode = Context.MODE_NAME_RESTORE; backupDirectory = (File) context.get(Context.BACKUP_DIRECTORY); logger.debug("Got backup directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backupDirectory.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backupDirectory.mkdirs(); } else if (!backupDirectory.exists()) { throw new PersistenceException("Backup directory {" + backupDirectory.getAbsolutePath() + "} does not exist."); } backup = new File(backupDirectory + "/" + getBackupName() + ".zip"); logger.debug("Got zip file {" + backup.getAbsolutePath() + "}"); } File _explodedDirectory = File.createTempFile("exploded-" + backup.getName() + "-", ".zip"); _explodedDirectory.mkdirs(); _explodedDirectory.delete(); backupDirectory = new File(_explodedDirectory.getParentFile(), _explodedDirectory.getName()); backupDirectory.mkdirs(); logger.debug("Created exploded directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backup.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backup.createNewFile(); } else if (!backup.exists()) { throw new PersistenceException("Backup file {" + backup.getAbsolutePath() + "} does not exist."); } if (newZip) return; ZipFile zip = new ZipFile(backup); Enumeration zipFileEntries = zip.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); logger.debug("Inflating: " + entry); File destFile = new File(backupDirectory, currentEntry); File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); if (!entry.isDirectory()) { InputStream in = null; OutputStream out = null; try { in = zip.getInputStream(entry); out = new FileOutputStream(destFile); IOUtils.copy(in, out); } finally { if (null != out) out.close(); if (null != in) in.close(); } } } } catch (IOException e) { logger.error("Unable to unzip {" + backup + "}", e); throw new PersistenceException(e); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static String hash(String arg) throws NoSuchAlgorithmException { String input = arg; String output; MessageDigest md = MessageDigest.getInstance("SHA"); md.update(input.getBytes()); output = Hex.encodeHexString(md.digest()); return output; } Code Sample 2: public static String md5(String plainText) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } ret = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ret; }
00
Code Sample 1: public VersionInfo getVersionInfo(String url) { try { XmlContentHandler handler = new XmlContentHandler(); XMLReader myReader = XMLReaderFactory.createXMLReader(); myReader.setContentHandler(handler); myReader.parse(new InputSource(new URL(url).openStream())); return handler.getVersionInfo(); } catch (SAXException e) { if (debug) { println("SAXException was thrown!"); e.printStackTrace(); } } catch (MalformedURLException e) { if (debug) { println("MalformedURLException was thrown!"); e.printStackTrace(); } } catch (IOException e) { if (debug) { println("IOException was thrown!"); e.printStackTrace(); } } return null; } Code Sample 2: private String hashmd5(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; }
11
Code Sample 1: public static String computeMD5(InputStream input) { InputStream digestStream = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); digestStream = new DigestInputStream(input, md5); IOUtils.copy(digestStream, new NullOutputStream()); return new String(Base64.encodeBase64(md5.digest()), "UTF-8"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(digestStream); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: public AudioInputStream getAudioInputStream(URL url, String userAgent) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReaderWorkaround.getAudioInputStream(URL,String): begin"); } long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED; URLConnection conn = url.openConnection(); boolean isShout = false; int toRead = 4; byte[] head = new byte[toRead]; if (userAgent != null) conn.setRequestProperty("User-Agent", userAgent); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Icy-Metadata", "1"); conn.setRequestProperty("Connection", "close"); BufferedInputStream bInputStream = new BufferedInputStream(conn.getInputStream()); bInputStream.mark(toRead); int read = bInputStream.read(head, 0, toRead); if ((read > 2) && (((head[0] == 'I') | (head[0] == 'i')) && ((head[1] == 'C') | (head[1] == 'c')) && ((head[2] == 'Y') | (head[2] == 'y')))) { isShout = true; } bInputStream.reset(); InputStream inputStream = null; if (isShout == true) { IcyInputStream icyStream = new IcyInputStream(bInputStream); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { String metaint = conn.getHeaderField("icy-metaint"); if (metaint != null) { IcyInputStream icyStream = new IcyInputStream(bInputStream, metaint); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { inputStream = bInputStream; } } AudioInputStream audioInputStream = null; try { audioInputStream = getAudioInputStream(inputStream, lFileLengthInBytes); } catch (UnsupportedAudioFileException e) { inputStream.close(); throw e; } catch (IOException e) { inputStream.close(); throw e; } if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReaderWorkaround.getAudioInputStream(URL,String): end"); } return audioInputStream; } Code Sample 2: @Override public String addUser(UserInfoItem user) throws DatabaseException { if (user == null) throw new NullPointerException("user"); if (user.getSurname() == null || "".equals(user.getSurname())) throw new NullPointerException("user.getSurname()"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; PreparedStatement insSt = null, updSt = null, seqSt = null; try { int modified = 0; if (user.getId() != null) { long id = Long.parseLong(user.getId()); updSt = getConnection().prepareStatement(UPDATE_USER_STATEMENT); updSt.setString(1, user.getName()); updSt.setString(2, user.getSurname()); updSt.setLong(3, id); modified = updSt.executeUpdate(); } else { insSt = getConnection().prepareStatement(INSERT_USER_STATEMENT); insSt.setString(1, user.getName()); insSt.setString(2, user.getSurname()); insSt.setBoolean(3, "m".equalsIgnoreCase(user.getSex())); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_CURR_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); } else { getConnection().rollback(); LOGGER.debug("DB has not been updated. -> rollback! Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } return retID; }
11
Code Sample 1: private void processar() { boolean bOK = false; String sSQL = "DELETE FROM FNSALDOLANCA WHERE CODEMP=? AND CODFILIAL=?"; try { state("Excluindo base atual de saldos..."); PreparedStatement ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("FNSALDOLANCA")); ps.executeUpdate(); ps.close(); state("Base excluida..."); bOK = true; } catch (SQLException err) { Funcoes.mensagemErro(this, "Erro ao excluir os saldos!\n" + err.getMessage(), true, con, err); err.printStackTrace(); } if (bOK) { bOK = false; sSQL = "SELECT CODPLAN,DATASUBLANCA,SUM(VLRSUBLANCA) VLRSUBLANCA FROM " + "FNSUBLANCA WHERE CODEMP=? AND CODFILIAL=? GROUP BY CODPLAN,DATASUBLANCA " + "ORDER BY CODPLAN,DATASUBLANCA"; try { state("Iniciando reconstru��o..."); PreparedStatement ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("FNLANCA")); ResultSet rs = ps.executeQuery(); String sPlanAnt = ""; double dSaldo = 0; bOK = true; int iFilialPlan = ListaCampos.getMasterFilial("FNPLANEJAMENTO"); int iFilialSaldo = ListaCampos.getMasterFilial("FNSALDOLANCA"); while (rs.next() && bOK) { if ("1010100000004".equals(rs.getString("CodPlan"))) { System.out.println("Debug"); } if (sPlanAnt.equals(rs.getString("CodPlan"))) { dSaldo += rs.getDouble("VLRSUBLANCA"); } else dSaldo = rs.getDouble("VLRSUBLANCA"); bOK = insereSaldo(iFilialSaldo, iFilialPlan, rs.getString("CodPlan"), rs.getDate("DataSubLanca"), dSaldo); sPlanAnt = rs.getString("CodPlan"); if ("1010100000004".equals(sPlanAnt)) { System.out.println("Debug"); } } ps.close(); state("Aguardando grava��o final..."); } catch (SQLException err) { bOK = false; Funcoes.mensagemErro(this, "Erro ao excluir os lan�amentos!\n" + err.getMessage(), true, con, err); err.printStackTrace(); } } try { if (bOK) { con.commit(); state("Registros processados com sucesso!"); } else { state("Registros antigos restaurados!"); con.rollback(); } } catch (SQLException err) { Funcoes.mensagemErro(this, "Erro ao relizar precedimento!\n" + err.getMessage(), true, con, err); err.printStackTrace(); } bRunProcesso = false; btProcessar.setEnabled(true); } Code Sample 2: public void addUser(String strUserName, String strPass, boolean isEncrypt) throws Exception { Connection con = null; PreparedStatement pstmt = null; try { con = DbForumFactory.getConnection(); con.setAutoCommit(false); int userID = DbSequenceManager.nextID(DbSequenceManager.USER); pstmt = con.prepareStatement(INSERT_USER); pstmt.setString(1, strUserName); if (isEncrypt) { pstmt.setString(2, SecurityUtil.md5ByHex(strPass)); } else { pstmt.setString(2, strPass); } pstmt.setString(3, ""); pstmt.setString(4, ""); pstmt.setString(5, ""); pstmt.setString(6, ""); pstmt.setString(7, ""); pstmt.setInt(8, userID); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = con.prepareStatement(INSERT_USERPROPS); pstmt.setString(1, ""); pstmt.setString(2, ""); pstmt.setString(3, ""); pstmt.setInt(4, 0); pstmt.setString(5, ""); pstmt.setInt(6, 0); pstmt.setInt(7, 0); pstmt.setString(8, ""); pstmt.setString(9, ""); pstmt.setString(10, ""); pstmt.setInt(11, 0); pstmt.setInt(12, 0); pstmt.setInt(13, 0); pstmt.setInt(14, 0); pstmt.setString(15, ""); pstmt.setString(16, ""); pstmt.setString(17, ""); pstmt.setString(18, ""); pstmt.setString(19, ""); pstmt.setString(20, ""); pstmt.setString(21, ""); pstmt.setString(22, ""); pstmt.setString(23, ""); pstmt.setInt(24, 0); pstmt.setInt(25, 0); pstmt.setInt(26, userID); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = con.prepareStatement(INSTER_USERGROUP); pstmt.setInt(1, 4); pstmt.setInt(2, userID); pstmt.setInt(3, 0); pstmt.executeUpdate(); con.commit(); } catch (Exception e) { try { con.rollback(); } catch (SQLException e1) { } log.error("insert user Error: " + e.toString()); } finally { DbForumFactory.closeDB(null, pstmt, null, con); } }
11
Code Sample 1: protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } } Code Sample 2: public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80), new UsernamePasswordCredentials("username", "password")); BasicHttpContext localcontext = new BasicHttpContext(); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", "some realm"); digestAuth.overrideParamter("nonce", "whatever"); localcontext.setAttribute("preemptive-auth", digestAuth); httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); httpclient.addResponseInterceptor(new PersistentDigest()); HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); entity.consumeContent(); } } } Code Sample 2: public static String MD5Encode(String password) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } return buf.toString(); } catch (NoSuchAlgorithmException e) { return password; } }
11
Code Sample 1: public static String calculateHA2(String uri) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes("GET", ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(uri, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: protected static String md5(String s) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); byte digest[] = md.digest(); StringBuffer result = new StringBuffer(); for (int i = 0; i < digest.length; i++) { result.append(Integer.toHexString(0xFF & digest[i])); } return result.toString(); }
11
Code Sample 1: private long generateNativeInstallExe(File nativeInstallFile, String instTemplate, File instClassFile) throws IOException { InputStream reader = getClass().getResourceAsStream("/" + instTemplate); ByteArrayOutputStream content = new ByteArrayOutputStream(); String installClassVarStr = "000000000000"; byte[] buf = new byte[installClassVarStr.length()]; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassVarStr.length()); int installClassStopPos = 0; long installClassOffset = reader.available(); int position = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallExe")); reader.read(buf, 0, buf.length); position = 1; for (int n = 0; n < 3; n++) { while ((!new String(buf).equals("clname_here_")) && (!new String(buf).equals("clstart_here")) && (!new String(buf).equals("clstop_here_"))) { content.write(buf[0]); int nextb = reader.read(); position++; shiftArray(buf); buf[buf.length - 1] = (byte) nextb; } if (new String(buf).equals("clname_here_")) { VAGlobals.printDebug(" clname_here_ found at " + (position - 1)); StringBuffer clnameBuffer = new StringBuffer(64); clnameBuffer.append(instClassName_); for (int i = clnameBuffer.length() - 1; i < 64; i++) { clnameBuffer.append('.'); } byte[] clnameBytes = clnameBuffer.toString().getBytes(); for (int i = 0; i < 64; i++) { content.write(clnameBytes[i]); position++; } reader.skip(64 - buf.length); reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstart_here")) { VAGlobals.printDebug(" clstart_here found at " + (position - 1)); buf = nf.format(installClassOffset).getBytes(); for (int i = 0; i < buf.length; i++) { content.write(buf[i]); position++; } reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstop_here_")) { VAGlobals.printDebug(" clstop_here_ found at " + (position - 1)); installClassStopPos = position - 1; content.write(buf); position += 12; reader.read(buf, 0, buf.length); } } content.write(buf); buf = new byte[2048]; int read = reader.read(buf); while (read > 0) { content.write(buf, 0, read); read = reader.read(buf); } reader.close(); FileInputStream classStream = new FileInputStream(instClassFile); read = classStream.read(buf); while (read > 0) { content.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); content.close(); byte[] contentBytes = content.toByteArray(); installClassVarStr = nf.format(contentBytes.length); byte[] installClassVarBytes = installClassVarStr.getBytes(); for (int i = 0; i < installClassVarBytes.length; i++) { contentBytes[installClassStopPos + i] = installClassVarBytes[i]; } FileOutputStream out = new FileOutputStream(nativeInstallFile); out.write(contentBytes); out.close(); return installClassOffset; } Code Sample 2: public static void copy(File src, File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
00
Code Sample 1: public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); } Code Sample 2: private Integer getInt(String sequence) throws NoSuchSequenceException { Connection conn = null; PreparedStatement read = null; PreparedStatement write = null; boolean success = false; try { conn = ds.getConnection(); conn.setTransactionIsolation(conn.TRANSACTION_REPEATABLE_READ); conn.setAutoCommit(false); read = conn.prepareStatement(SELECT_SQL); read.setString(1, sequence); ResultSet readRs = read.executeQuery(); if (!readRs.next()) { throw new NoSuchSequenceException(); } int currentSequenceId = readRs.getInt(1); int currentSequenceValue = readRs.getInt(2); Integer currentSequenceValueInteger = new Integer(currentSequenceValue); write = conn.prepareStatement(UPDATE_SQL); write.setInt(1, currentSequenceValue + 1); write.setInt(2, currentSequenceId); int rowsAffected = write.executeUpdate(); if (rowsAffected == 1) { success = true; return currentSequenceValueInteger; } else { logger.error("Something strange has happened. The row count was not 1, but was " + rowsAffected); return currentSequenceValueInteger; } } catch (SQLException sqle) { logger.error("Table based id generation failed : "); logger.error(sqle.getMessage()); return new Integer(0); } finally { if (read != null) { try { read.close(); } catch (Exception e) { } } if (write != null) { try { write.close(); } catch (Exception e) { } } if (conn != null) { try { if (success) { conn.commit(); } else { conn.rollback(); } conn.close(); } catch (Exception e) { } } } }
11
Code Sample 1: public void testIntegrityViolation() throws Exception { if (getDialect() instanceof MySQLMyISAMDialect) { reportSkip("MySQL (ISAM) does not support FK violation checking", "exception conversion"); return; } SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); Session session = openSession(); session.beginTransaction(); Connection connection = session.connection(); PreparedStatement ps = null; try { ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"); ps.setLong(1, 52134241); ps.setLong(2, 5342); ps.executeUpdate(); fail("INSERT should have failed"); } catch (SQLException sqle) { JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!"); JDBCException jdbcException = converter.convert(sqle, null, null); assertEquals("Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class, jdbcException.getClass()); ConstraintViolationException ex = (ConstraintViolationException) jdbcException; System.out.println("Violated constraint name: " + ex.getConstraintName()); } finally { if (ps != null) { try { ps.close(); } catch (Throwable ignore) { } } } session.getTransaction().rollback(); session.close(); } Code Sample 2: public void deleteGroup(String groupID) throws XregistryException { try { Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_GROUP_SQL_MAIN); statement1.setString(1, groupID); int updateCount = statement1.executeUpdate(); if (updateCount == 0) { throw new XregistryException("Database is not updated, Can not find such Group " + groupID); } if (cascadingDeletes) { PreparedStatement statement2 = connection.prepareStatement(DELETE_GROUP_SQL_DEPEND); statement2.setString(1, groupID); statement2.setString(2, groupID); statement2.executeUpdate(); } connection.commit(); groups.remove(groupID); log.info("Delete Group " + groupID + (cascadingDeletes ? " with cascading deletes " : "")); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } }
00
Code Sample 1: public APIResponse create(User user) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/user/create").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(user, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Create User Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; } Code Sample 2: private static List retrieveQuotes(Report report, Symbol symbol, String suffix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, suffix, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
00
Code Sample 1: public static boolean verify(String password, String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } byte[] data = Base64.decode(base64.toCharArray()); byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); } Code Sample 2: public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); }
00
Code Sample 1: private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); } Code Sample 2: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); URL url; URLConnection urlConn; DataOutputStream cgiInput; url = new URL("http://localhost:8080/ListeOnLine/Target"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cgiInput = new DataOutputStream(urlConn.getOutputStream()); String content = "param1=" + URLEncoder.encode("first parameter") + "&param2=" + URLEncoder.encode("the second one..."); cgiInput.writeBytes(content); cgiInput.flush(); cgiInput.close(); BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); PrintWriter servletOutput = response.getWriter(); servletOutput.print("<html><body><h1>This is the Source Servlet</h1><p />"); String line = null; while (null != (line = cgiOutput.readLine())) { servletOutput.println(line); } cgiOutput.close(); servletOutput.print("</body></html>"); servletOutput.close(); }
11
Code Sample 1: private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); } Code Sample 2: public void copyFile2(String src, String dest) throws IOException { String newLine = System.getProperty("line.separator"); FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + QZ.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(QZ.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
11
Code Sample 1: public static List<PluginInfo> getPluginInfos(String urlRepo) throws MalformedURLException, IOException { XStream xStream = new XStream(); xStream.alias("plugin", PluginInfo.class); xStream.alias("plugins", List.class); List<PluginInfo> infos = null; URL url; BufferedReader in = null; StringBuilder buffer = new StringBuilder(); try { url = new URL(urlRepo); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(RemotePluginsManager.class.getName()).log(Level.SEVERE, null, ex); } } infos = (List<PluginInfo>) xStream.fromXML(buffer.toString()); return infos; } Code Sample 2: protected void discoverRegistryEntries() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFactory.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormat.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: 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); } } Code Sample 2: public int doEndTag() throws JspException { HttpSession session = pageContext.getSession(); try { IntactUserI user = (IntactUserI) session.getAttribute(Constants.USER_KEY); String urlStr = user.getSourceURL(); if (urlStr == null) { return EVAL_PAGE; } URL url = null; try { url = new URL(urlStr); } catch (MalformedURLException me) { String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("The source is malformed : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } StringBuffer httpContent = new StringBuffer(); httpContent.append("<!-- URL : " + urlStr + "-->"); String tmpLine; try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((tmpLine = reader.readLine()) != null) { httpContent.append(tmpLine); } reader.close(); } catch (IOException ioe) { user.resetSourceURL(); String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("Unable to display the source at : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } pageContext.getOut().write(httpContent.toString()); } catch (Exception e) { e.printStackTrace(); throw new JspException("Error when trying to get HTTP content"); } return EVAL_PAGE; }
00
Code Sample 1: public void loadJarFile(String jarFileNameParam) throws KExceptionClass { jarFileName = jarFileNameParam; { String message = "Loading resource file ["; message += jarFileName; message += "]..."; log.log(this, message); } try { URL url = new URL(jarFileName); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarConnection.setUseCaches(false); JarFile jarFile = jarConnection.getJarFile(); Enumeration jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { ZipEntry zipEntrie = (ZipEntry) jarEntries.nextElement(); { String message = "Scanning ["; message += jarFileName; message += "] found ["; message += describeEntry(zipEntrie); message += "]"; log.log(this, message); } htSizes.put(zipEntrie.getName(), new Integer((int) zipEntrie.getSize())); } ; jarFile.close(); BufferedInputStream inputBuffer = new BufferedInputStream(jarConnection.getJarFileURL().openStream()); ZipInputStream input = new ZipInputStream(inputBuffer); ZipEntry zipEntrie = null; while ((zipEntrie = input.getNextEntry()) != null) { if (zipEntrie.isDirectory()) continue; { String message = "Scanning ["; message += jarFileName; message += "] loading ["; message += zipEntrie.getName(); message += "] for ["; message += zipEntrie.getSize(); message += "] bytes."; log.log(this, message); } int size = (int) zipEntrie.getSize(); if (size == -1) { size = ((Integer) htSizes.get(zipEntrie.getName())).intValue(); } ; byte[] entrieData = new byte[(int) size]; int offset = 0; int dataRead = 0; while (((int) size - offset) > 0) { dataRead = input.read(entrieData, offset, (int) size - offset); if (dataRead == -1) break; offset += dataRead; } htJarContents.put(zipEntrie.getName(), entrieData); if (debugOn) { System.out.println(zipEntrie.getName() + " offset=" + offset + ",size=" + size + ",csize=" + zipEntrie.getCompressedSize()); } ; } ; } catch (Exception error) { String message = "Error loading data from JAR file ["; message += error.toString(); message += "]"; throw new KExceptionClass(message, new KExceptionClass(error.toString(), null)); } ; } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + 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 = gd.getConexion().createStatement(); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
00
Code Sample 1: static boolean generateKey() throws NoSuchAlgorithmException { java.util.Random rand = new Random(reg_name.hashCode() + System.currentTimeMillis()); DecimalFormat vf = new DecimalFormat("000"); ccKey = keyProduct + FIELD_SEPERATOR + keyType + FIELD_SEPERATOR + keyQuantity + FIELD_SEPERATOR + vf.format(lowMajorVersion) + FIELD_SEPERATOR + vf.format(lowMinorVersion) + FIELD_SEPERATOR + vf.format(highMajorVersion) + FIELD_SEPERATOR + vf.format(highMinorVersion) + FIELD_SEPERATOR + reg_name + FIELD_SEPERATOR + Integer.toHexString(rand.nextInt()).toUpperCase(); byte[] md5; MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(ccKey.getBytes()); md.update(FIELD_SEPERATOR.getBytes()); md.update(zuonicsPassword.getBytes()); md5 = md.digest(); userKey = ccKey + FIELD_SEPERATOR; for (int i = 0; i < md5.length; i++) userKey += Integer.toHexString(md5[i]).toUpperCase(); return true; } Code Sample 2: public void performUpdates(List<PackageDescriptor> downloadList, ProgressListener progressListener) throws IOException, UpdateServiceException_Exception { int i = 0; try { for (PackageDescriptor desc : downloadList) { String urlString = service.getDownloadURL(desc.getPackageId(), desc.getVersion(), desc.getPlatformName()); int minProgress = 20 + 80 * i / downloadList.size(); int maxProgress = 20 + 80 * (i + 1) / downloadList.size(); boolean incremental = UpdateManager.isIncrementalUpdate(); if (desc.getPackageTypeName().equals("RAPIDMINER_PLUGIN")) { ManagedExtension extension = ManagedExtension.getOrCreate(desc.getPackageId(), desc.getName(), desc.getLicenseName()); String baseVersion = extension.getLatestInstalledVersionBefore(desc.getVersion()); incremental &= baseVersion != null; URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(baseVersion, "UTF-8") : "")).toURL(); if (incremental) { LogService.getRoot().info("Updating " + desc.getPackageId() + " incrementally."); try { updatePluginIncrementally(extension, openStream(url, progressListener, minProgress, maxProgress), baseVersion, desc.getVersion()); } catch (IOException e) { LogService.getRoot().warning("Incremental Update failed. Trying to fall back on non incremental Update..."); incremental = false; } } if (!incremental) { LogService.getRoot().info("Updating " + desc.getPackageId() + "."); updatePlugin(extension, openStream(url, progressListener, minProgress, maxProgress), desc.getVersion()); } extension.addAndSelectVersion(desc.getVersion()); } else { URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(RapidMiner.getLongVersion(), "UTF-8") : "")).toURL(); LogService.getRoot().info("Updating RapidMiner core."); updateRapidMiner(openStream(url, progressListener, minProgress, maxProgress), desc.getVersion()); } i++; progressListener.setCompleted(20 + 80 * i / downloadList.size()); } } catch (URISyntaxException e) { throw new IOException(e); } finally { progressListener.complete(); } }
11
Code Sample 1: public static String getMD5(String s) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(s.getBytes()); byte[] result = md5.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < result.length; i++) { hexString.append(String.format("%02x", 0xFF & result[i])); } return hexString.toString(); } Code Sample 2: public static String getSHA1(String data) throws NoSuchAlgorithmException { String addr; data = data.toLowerCase(Locale.getDefault()); if (data.startsWith("mailto:")) { addr = data.substring(7); } else { addr = data; } MessageDigest md = MessageDigest.getInstance("SHA"); StringBuffer sb = new StringBuffer(); md.update(addr.getBytes()); byte[] digest = md.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); sb.append(hex); } return sb.toString(); }
00
Code Sample 1: private void initializeTree() { InputStreamReader reader = null; BufferedReader buffReader = null; try { for (int i = 0; i < ORDER.length; i++) { int index = ORDER[i]; String indexName = index < 10 ? "0" + index : (index > 20 ? "big" : "" + index); URL url = EmptyClass.class.getResource("engchar" + indexName + ".dic"); logger.info("... Loading: " + "engchar" + indexName + ".dic = {" + url + "}"); reader = new InputStreamReader(url.openStream()); buffReader = new BufferedReader(reader); String line = null; String word = null; do { line = buffReader.readLine(); if (line != null) { boolean plural = line.endsWith("/S"); boolean forbidden = line.endsWith("/X"); if (plural) { int stringIndex = line.indexOf("/S"); word = new String(line.substring(0, stringIndex)); } else if (forbidden) { int stringIndex = line.indexOf("/X"); word = new String(line.substring(0, stringIndex)); } else { word = line.toString(); } if (tree == null) { tree = new BKTree(); } tree.insertDictionaryWord(word, plural, forbidden); } } while (line != null); } logger.debug("Loading supplemental dictionary..."); List<String> listOfWords = KSupplementalDictionaryUtil.getWords(); for (String word : listOfWords) { tree.insertDictionaryWord(word, false, false); } initialized = true; } catch (Exception exception) { logger.error("Error", exception); } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { } } if (buffReader != null) { try { buffReader.close(); } catch (Exception ex) { } } } } Code Sample 2: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
00
Code Sample 1: public boolean copyDirectoryTree(File srcPath, File dstPath) { try { if (srcPath.isDirectory()) { if (!dstPath.exists()) dstPath.mkdir(); String files[] = srcPath.list(); for (int i = 0; i < files.length; i++) copyDirectoryTree(new File(srcPath, files[i]), new File(dstPath, files[i])); } else { if (!srcPath.exists()) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath + "' does not exist.\n"; lastErrMsgLog = errMsgLog; return (false); } else { InputStream in = new FileInputStream(srcPath); OutputStream out = new FileOutputStream(dstPath); byte[] buf = new byte[10240]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } } return (true); } catch (Exception e) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath.getName() + "' to '" + dstPath.getName() + "\n " + e + "\n"; lastErrMsgLog = errMsgLog; return (false); } } Code Sample 2: protected void registerClasses() throws PrintException { if (!init) { try { Enumeration<URL> somethingToRegister = this.getClass().getClassLoader().getResources("META-INF/" + getClass().getSimpleName() + ".properties"); while (somethingToRegister.hasMoreElements()) { URL url = (URL) somethingToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); try { Class cls = Class.forName(line); cls.newInstance(); log.debug("class " + line + " registered " + url); } catch (ClassNotFoundException e) { log.error("class " + line + " not found " + url, e); } catch (InstantiationException e) { log.error("class " + line + " not found " + url, e); } catch (IllegalAccessException e) { log.error("class " + line + " not found " + url, e); } line = buff.readLine(); } buff.close(); in.close(); } } catch (IOException e) { throw new PrintException(e.getMessage(), e); } init = true; } }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: protected static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection c = url.openConnection(); c.setConnectTimeout(2000); IOUtils.copy(c.getInputStream(), output); return output.toString(); } Code Sample 2: public HttpURLHandler(URL url, String requestMethod, Map<String, String> parameters, String outputEncoding) throws IOException { logger.debug("Creating http url handler for: " + url + "; using method: " + requestMethod + "; with parameters: " + parameters); if (url == null) throw new IllegalArgumentException("Null pointer in url"); if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) throw new IllegalArgumentException("Illegal url protocol: \"" + url.getProtocol() + "\"; must be \"http\" or \"https\""); if (requestMethod == null) throw new IllegalArgumentException("Null pointer in requestMethod"); if (!"GET".equals(requestMethod) && !"POST".equals(requestMethod)) throw new IllegalArgumentException("Illegal request method: " + requestMethod + "; must be \"GET\" or \"POST\""); if (parameters == null) throw new IllegalArgumentException("Null pointer in parameters"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); connection.setRequestMethod(requestMethod); connection.setUseCaches(false); if (EMPTY_MAP.equals(parameters)) { connection.setDoOutput(false); } else { connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); writeParameters(out, parameters, outputEncoding); out.close(); } inputStream = connection.getInputStream(); }
11
Code Sample 1: private String MD5(String s) { Log.d("MD5", "Hashing '" + s + "'"); String hash = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); hash = new BigInteger(1, m.digest()).toString(16); Log.d("MD5", "Hash: " + hash); } catch (Exception e) { Log.e("MD5", e.getMessage()); } return hash; } Code Sample 2: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public void mousePressed(MouseEvent e) { bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(bannerURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); HttpHost host = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); String targetURL = host.toURI() + request.getURI(); DesktopUtil.browseAndWarn(targetURL, bannerLbl); EntityUtils.consume(entity); } catch (Exception ex) { NotifyUtil.error("Banner Error", "Could not open the default web browser.", ex, false); } finally { method.abort(); } bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } Code Sample 2: public void setPassword(UserType user, String clearPassword) { try { Random r = new Random(); String newSalt = Long.toString(Math.abs(r.nextLong())); MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(newSalt.getBytes("UTF-8")); md.update(clearPassword.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); user.setPassword(encodedString); user.setSalt(newSalt); this.markModified(user); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(errorMessage, ex); GlobalUITools.displayFatalExceptionMessage(null, errorMessage, ex, true); } }
00
Code Sample 1: private static URL getURL(String name) throws EfreetException { URL url = ClassLoader.getSystemResource(name + ".xml"); try { if (url == null) { try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); String xmlFileDir = (String) envContext.lookup("xml/efreet"); url = new URL("file:" + xmlFileDir + "/" + name + ".xml"); } catch (NameNotFoundException nnfe) { logger.warn("Name not found on context "); } catch (NamingException e) { logger.error("Error retrieving Context : ", e); } } try { if (url != null) { url.openConnection(); } } catch (FileNotFoundException fnfe) { url = null; } if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(name + ".xml"); } } catch (IOException ioe) { logger.error("Error reading XML file", ioe); throw new EfreetException(ioe.getMessage()); } return url; } Code Sample 2: public HttpURLHandler(URL url, String requestMethod, Map<String, String> parameters, String outputEncoding) throws IOException { logger.debug("Creating http url handler for: " + url + "; using method: " + requestMethod + "; with parameters: " + parameters); if (url == null) throw new IllegalArgumentException("Null pointer in url"); if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) throw new IllegalArgumentException("Illegal url protocol: \"" + url.getProtocol() + "\"; must be \"http\" or \"https\""); if (requestMethod == null) throw new IllegalArgumentException("Null pointer in requestMethod"); if (!"GET".equals(requestMethod) && !"POST".equals(requestMethod)) throw new IllegalArgumentException("Illegal request method: " + requestMethod + "; must be \"GET\" or \"POST\""); if (parameters == null) throw new IllegalArgumentException("Null pointer in parameters"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); connection.setRequestMethod(requestMethod); connection.setUseCaches(false); if (EMPTY_MAP.equals(parameters)) { connection.setDoOutput(false); } else { connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); writeParameters(out, parameters, outputEncoding); out.close(); } inputStream = connection.getInputStream(); }
00
Code Sample 1: public void getFile(String url, String filepath) throws BggException { System.out.println(url); int retry = retryCount + 1; lastURL = url; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; BufferedInputStream bis = null; OutputStream osw = null; try { con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); setHeaders(con); con.setRequestMethod("GET"); responseCode = con.getResponseCode(); bis = new BufferedInputStream(con.getInputStream()); int data; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filepath)); while ((data = bis.read()) != -1) bos.write(data); bos.flush(); bos.close(); break; } finally { try { bis.close(); } catch (Exception ignore) { } try { osw.close(); } catch (Exception ignore) { } try { con.disconnect(); } catch (Exception ignore) { } } } catch (IOException ioe) { if (responseCode == UNAUTHORIZED || responseCode == FORBIDDEN) { throw new BggException(ioe.getMessage(), responseCode); } if (retriedCount == retryCount) { throw new BggException(ioe.getMessage(), responseCode); } } try { Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private String loadStatusResult() { try { URL url = new URL(getServerUrl()); InputStream input = url.openStream(); InputStreamReader is = new InputStreamReader(input, "utf-8"); BufferedReader reader = new BufferedReader(is); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e1) { e1.printStackTrace(); return null; } catch (IOException e2) { e2.printStackTrace(); return null; } } Code Sample 2: @Override public String encodePassword(final String password, final Object salt) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(salt.toString().getBytes()); byte[] passwordHash = digest.digest(password.getBytes()); Base64 encoder = new Base64(); byte[] encoded = encoder.encode(passwordHash); return new String(encoded); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: public static <T extends Comparable<T>> void BubbleSortComparable1(T[] num) { int j; boolean flag = true; // set flag to true to begin first pass T temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (j = 0; j < num.length - 1; j++) { if (num[j].compareTo(num[j + 1]) > 0) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } } Code Sample 2: public GeocodeResponse getGKCoordinateFromAddress(SearchAddressRequest searchAddressRequest) { GeocodeResponse result = null; String adress = null; if (searchAddressRequest.getAdressTextField() != null) adress = searchAddressRequest.getAdressTextField().getText(); if (adress == null || adress.length() == 0) adress = " "; String postRequest = ""; postRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" + "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/xls \n" + "http://gdi3d.giub.uni-bonn.de:8080/openls-lus/schemas/LocationUtilityService.xsd\" version=\"1.1\"> \n" + " <xls:RequestHeader srsName=\"EPSG:" + Navigator.getEpsg_code() + "\"/> \n" + " <xls:Request methodName=\"GeocodeRequest\" requestID=\"123456789\" version=\"1.1\"> \n" + " <xls:GeocodeRequest> \n" + " <xls:Address countryCode=\"DE\"> \n" + " <xls:freeFormAddress>" + adress + "</xls:freeFormAddress> \n" + " </xls:Address> \n" + " </xls:GeocodeRequest> \n" + " </xls:Request> \n" + "</xls:XLS> \n"; if (Navigator.isVerbose()) { System.out.println("OpenLSGeocoder postRequest " + postRequest); } String errorMessage = ""; try { System.out.println("contacting " + serviceEndPoint); URL u = new URL(serviceEndPoint); HttpURLConnection urlc = (HttpURLConnection) u.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); urlc.setAllowUserInteraction(false); urlc.setRequestMethod("POST"); urlc.setRequestProperty("Content-Type", "application/xml"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); PrintWriter xmlOut = null; xmlOut = new java.io.PrintWriter(urlc.getOutputStream()); xmlOut.write(postRequest); xmlOut.flush(); xmlOut.close(); InputStream is = urlc.getInputStream(); result = new GeocodeResponse(); XLSDocument xlsResponse = XLSDocument.Factory.parse(is); XLSType xlsTypeResponse = xlsResponse.getXLS(); Node node0 = xlsTypeResponse.getDomNode(); NodeList nodes1 = node0.getChildNodes(); for (int i = 0; i < nodes1.getLength(); i++) { Node node1 = nodes1.item(i); NodeList nodes2 = node1.getChildNodes(); for (int j = 0; j < nodes2.getLength(); j++) { Node node2 = nodes2.item(j); NodeList nodes3 = node2.getChildNodes(); for (int k = 0; k < nodes3.getLength(); k++) { Node node3 = nodes3.item(k); String nodeName = node3.getNodeName(); if (nodeName.equalsIgnoreCase("xls:GeocodeResponseList")) { net.opengis.xls.GeocodeResponseListDocument gcrld = net.opengis.xls.GeocodeResponseListDocument.Factory.parse(node3); net.opengis.xls.GeocodeResponseListType geocodeResponseList = gcrld.getGeocodeResponseList(); result.setGeocodeResponseList(geocodeResponseList); } } } } is.close(); } catch (java.net.ConnectException ce) { JOptionPane.showMessageDialog(null, "no connection to geocoder", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (SocketTimeoutException ste) { ste.printStackTrace(); errorMessage += "<p>Time Out Exception, Server is not responding</p>"; } catch (IOException ioe) { ioe.printStackTrace(); errorMessage += "<p>IO Exception</p>"; } catch (XmlException xmle) { xmle.printStackTrace(); errorMessage += "<p>Error occured during parsing the XML response</p>"; } if (!errorMessage.equals("")) { System.out.println("\nerrorMessage: " + errorMessage + "\n\n"); JLabel label1 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: bold;}--></style></head><body><span class=\"Stil2\">Geocoder Error</span></body></html>"); JLabel label2 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + errorMessage + "<br>" + "<p>please check Java console. If problem persits, please report to system manager</p>" + "</span></body></html>"); Object[] objects = { label1, label2 }; JOptionPane.showMessageDialog(null, objects, "Error Message", JOptionPane.ERROR_MESSAGE); return null; } return result; }
00
Code Sample 1: public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } } Code Sample 2: private void init() { synchronized (cachedProperties) { if (firstTime) { try { Enumeration<URL> configFiles; configFiles = classloader.getResources(CONFIG_LOCATION); if (configFiles == null) { logger.info("No configuration file ({}) found in the classpath.", CONFIG_LOCATION); return; } firstTime = false; boolean alreadyLoaded = false; while (configFiles.hasMoreElements()) { final URL url = configFiles.nextElement(); if (!alreadyLoaded) { final InputStream is = url.openStream(); cachedProperties.load(is); is.close(); logger.info("XmlFieldFactory configuration loaded from the file {}", url); } else { logger.info("An other XmlFieldFactory configuration file is found in the classpath. This file won't be loaded {}", url); } } } catch (IOException e) { logger.error("An error occur during the XmlFieldFActory initialization", e); } } } }
00
Code Sample 1: public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); } Code Sample 2: private static InputStream stream(String input) { try { if (input.startsWith("http://")) return URIFactory.url(input).openStream(); else return stream(new File(input)); } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException { if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength); if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'"); HashCash result = new HashCash(); MessageDigest md = MessageDigest.getInstance("SHA1"); result.myResource = resource; result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions); result.myDate = date; result.myVersion = version; String prefix; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); switch(version) { case 0: prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); md.reset(); md.update(result.myToken.getBytes()); result.myValue = numberOfLeadingZeros(md.digest()); break; case 1: result.myValue = value; prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); break; default: throw new IllegalArgumentException("Only supported versions are 0 and 1"); } return result; } Code Sample 2: public static void loadMemcachedConfigFromURL(URL url, XMLInputFactory factory, List<MemcachedClientConfig> memcachedClientconfigs, List<MemcachedClientSocketPoolConfig> memcachedClientSocketPoolConfigs, List<MemcachedClientClusterConfig> memcachedClientClusterConfig) { MemcachedClientConfig node = null; MemcachedClientSocketPoolConfig socketnode = null; MemcachedClientClusterConfig clusternode = null; InputStream in = null; XMLEventReader r = null; try { in = url.openStream(); r = factory.createXMLEventReader(in); String servers = null; String weights = null; while (r.hasNext()) { XMLEvent event = r.nextEvent(); if (event.isStartElement()) { StartElement start = event.asStartElement(); String tag = start.getName().getLocalPart(); if (tag.equalsIgnoreCase("client")) { node = new MemcachedClientConfig(); if (start.getAttributeByName(new QName("", "name")) != null) node.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client name can't not be null!"); if (start.getAttributeByName(new QName("", "socketpool")) != null) node.setSocketPool(start.getAttributeByName(new QName("", "socketpool")).getValue()); else throw new RuntimeException("memcached client socketpool can't not be null!"); if (start.getAttributeByName(new QName("", "compressEnable")) != null) node.setCompressEnable(Boolean.parseBoolean(start.getAttributeByName(new QName("", "compressEnable")).getValue())); else node.setCompressEnable(true); if (start.getAttributeByName(new QName("", "defaultEncoding")) != null) node.setDefaultEncoding(start.getAttributeByName(new QName("", "defaultEncoding")).getValue()); else node.setDefaultEncoding("UTF-8"); continue; } if (tag.equalsIgnoreCase("errorHandler") && node != null) { event = r.peek(); if (event.isCharacters()) { node.setErrorHandler(event.asCharacters().getData()); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("socketpool")) { socketnode = new MemcachedClientSocketPoolConfig(); servers = null; weights = null; if (start.getAttributeByName(new QName("", "name")) != null) socketnode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client socketpool name can't not be null!"); if (start.getAttributeByName(new QName("", "failover")) != null) socketnode.setFailover(Boolean.parseBoolean(start.getAttributeByName(new QName("", "failover")).getValue())); if (start.getAttributeByName(new QName("", "initConn")) != null) socketnode.setInitConn(Integer.parseInt(start.getAttributeByName(new QName("", "initConn")).getValue())); if (start.getAttributeByName(new QName("", "minConn")) != null) socketnode.setMinConn(Integer.parseInt(start.getAttributeByName(new QName("", "minConn")).getValue())); if (start.getAttributeByName(new QName("", "maxConn")) != null) socketnode.setMaxConn(Integer.parseInt(start.getAttributeByName(new QName("", "maxConn")).getValue())); if (start.getAttributeByName(new QName("", "maintSleep")) != null) socketnode.setMaintSleep(Integer.parseInt(start.getAttributeByName(new QName("", "maintSleep")).getValue())); if (start.getAttributeByName(new QName("", "nagle")) != null) socketnode.setNagle(Boolean.parseBoolean(start.getAttributeByName(new QName("", "nagle")).getValue())); if (start.getAttributeByName(new QName("", "socketTO")) != null) socketnode.setSocketTo(Integer.parseInt(start.getAttributeByName(new QName("", "socketTO")).getValue())); if (start.getAttributeByName(new QName("", "maxIdle")) != null) socketnode.setMaxIdle(Integer.parseInt(start.getAttributeByName(new QName("", "maxIdle")).getValue())); if (start.getAttributeByName(new QName("", "aliveCheck")) != null) socketnode.setAliveCheck(Boolean.parseBoolean(start.getAttributeByName(new QName("", "aliveCheck")).getValue())); continue; } if (tag.equalsIgnoreCase("servers") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { servers = event.asCharacters().getData(); socketnode.setServers(servers); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("weights") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { weights = event.asCharacters().getData(); socketnode.setWeights(weights); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("cluster")) { clusternode = new MemcachedClientClusterConfig(); if (start.getAttributeByName(new QName("", "name")) != null) clusternode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached cluster name can't not be null!"); if (start.getAttributeByName(new QName("", "mode")) != null) clusternode.setMode(start.getAttributeByName(new QName("", "mode")).getValue()); continue; } if (tag.equalsIgnoreCase("memCachedClients") && clusternode != null) { event = r.peek(); if (event.isCharacters()) { String clients = event.asCharacters().getData(); if (clients != null && !clients.equals("")) { clusternode.setMemCachedClients(clients.split(",")); } r.nextEvent(); } continue; } } if (event.isEndElement()) { EndElement end = event.asEndElement(); if (node != null && end.getName().getLocalPart().equalsIgnoreCase("client")) { memcachedClientconfigs.add(node); Logger.info(new StringBuilder().append(" add memcachedClient config :").append(node.getName())); continue; } if (socketnode != null && end.getName().getLocalPart().equalsIgnoreCase("socketpool")) { memcachedClientSocketPoolConfigs.add(socketnode); Logger.info(new StringBuilder().append(" add socketpool config :").append(socketnode.getName())); continue; } if (clusternode != null && end.getName().getLocalPart().equalsIgnoreCase("cluster")) { memcachedClientClusterConfig.add(clusternode); Logger.info(new StringBuilder().append(" add cluster config :").append(clusternode.getName())); continue; } } } } catch (Exception e) { Logger.error(new StringBuilder("MemcachedManager loadConfig error !").append(" config url :").append(url.getFile()).toString()); node = null; } finally { try { if (r != null) r.close(); if (in != null) in.close(); r = null; in = null; } catch (Exception ex) { throw new RuntimeException("processConfigURL error !", ex); } } }
00
Code Sample 1: protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } } Code Sample 2: @Test public void testMark() throws IllegalArgumentException, IOException { Assert.assertNotNull(this.m_detector); File f = new File("testdocuments/voiddocument/Voiderror.htm"); Assert.assertTrue("Test file " + f.getAbsolutePath() + " does not exist. ", f.exists()); URL url = f.toURL(); this.m_detector.detectCodepage(url.openStream(), 200); }
00
Code Sample 1: @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getLocalPrincipal", args = { }) public final void test_getLocalPrincipal() { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getLocalPrincipal(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } try { HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); assertNull(con.getLocalPrincipal()); con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); assertNotNull("Local principal is null", con.getLocalPrincipal()); } catch (Exception e) { fail("Unexpected exception " + e); } } Code Sample 2: byte[] makeIDPFXORMask() { if (idpfMask == null) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); String temp = strip(getPrimaryIdentifier()); sha.update(temp.getBytes("UTF-8"), 0, temp.length()); idpfMask = sha.digest(); } catch (NoSuchAlgorithmException e) { System.err.println("No such Algorithm (really, did I misspell SHA-1?"); System.err.println(e.toString()); return null; } catch (IOException e) { System.err.println("IO Exception. check out mask.write..."); System.err.println(e.toString()); return null; } } return idpfMask; }
00
Code Sample 1: public DicomReader(URL url) throws java.io.IOException { final URLConnection u = url.openConnection(); final int size = u.getContentLength(); final byte[] array = new byte[size]; int bytes_read = 0; final DataInputStream in = new DataInputStream(u.getInputStream()); while (bytes_read < size) { bytes_read += in.read(array, bytes_read, size - bytes_read); } in.close(); this.dHR = new DicomHeaderReader(array); h = dHR.getRows(); w = dHR.getColumns(); highBit = dHR.getHighBit(); bitsStored = dHR.getBitStored(); bitsAllocated = dHR.getBitAllocated(); n = (bitsAllocated / 8); signed = (dHR.getPixelRepresentation() == 1); this.pixData = dHR.getPixels(); ignoreNegValues = true; samplesPerPixel = dHR.getSamplesPerPixel(); numberOfFrames = dHR.getNumberOfFrames(); dbg("Number of Frames " + numberOfFrames); } Code Sample 2: public SessionManager(String username) { try { url = new URL("http://" + username + ".bebo.com"); conn = url.openConnection(); } catch (MalformedURLException ex) { Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex); } }
11
Code Sample 1: public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException { log.debug("copyLocalFileAsTempFileInExternallyAccessableDir"); File f = this.createTempFileInExternallyAccessableDir(); FileChannel srcChannel = new FileInputStream(localFileRef).getChannel(); FileChannel dstChannel = new FileOutputStream(f).getChannel(); log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef + " to dest-outputStream: " + f.getAbsolutePath()); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath()); return f; } Code Sample 2: public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); }
11
Code Sample 1: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(QZ.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(QZ.PHRASES.getPhrase("26") + " " + QZ.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(QZ.PHRASES.getPhrase("19") + dest_name + QZ.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(QZ.PHRASES.getPhrase("31")); } else throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } } Code Sample 2: private static Collection<String> createTopLevelFiles(Configuration configuration, Collections collections, Sets sets) throws FlickrException, SAXException, IOException, JDOMException, TransformerException { Collection<String> createdFiles = new HashSet<String>(); File toplevelXmlFilename = getToplevelXmlFilename(configuration.photosBaseDirectory); Logger.getLogger(FlickrDownload.class).info("Creating XML file " + toplevelXmlFilename.getAbsolutePath()); MediaIndexer indexer = new XmlMediaIndexer(configuration); Element toplevel = new Element("flickr").addContent(XmlUtils.createApplicationXml()).addContent(XmlUtils.createUserXml(configuration)).addContent(collections.createTopLevelXml()).addContent(sets.createTopLevelXml()).addContent(new Stats(sets).createStatsXml(indexer)); createdFiles.addAll(indexer.writeIndex()); XmlUtils.outputXmlFile(toplevelXmlFilename, toplevel); createdFiles.add(toplevelXmlFilename.getName()); Logger.getLogger(FlickrDownload.class).info("Copying support files and performing XSLT transformations"); IOUtils.copyToFileAndCloseStreams(XmlUtils.class.getResourceAsStream("xslt/" + PHOTOS_CSS_FILENAME), new File(configuration.photosBaseDirectory, PHOTOS_CSS_FILENAME)); createdFiles.add(PHOTOS_CSS_FILENAME); IOUtils.copyToFileAndCloseStreams(XmlUtils.class.getResourceAsStream("xslt/" + PLAY_ICON_FILENAME), new File(configuration.photosBaseDirectory, PLAY_ICON_FILENAME)); createdFiles.add(PLAY_ICON_FILENAME); XmlUtils.performXsltTransformation(configuration, "all_sets.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, ALL_SETS_HTML_FILENAME)); createdFiles.add(ALL_SETS_HTML_FILENAME); XmlUtils.performXsltTransformation(configuration, "all_collections.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, ALL_COLLECTIONS_HTML_FILENAME)); createdFiles.add(ALL_COLLECTIONS_HTML_FILENAME); createdFiles.add(Collections.COLLECTIONS_ICON_DIRECTORY); XmlUtils.performXsltTransformation(configuration, "stats.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, STATS_HTML_FILENAME)); createdFiles.add(STATS_HTML_FILENAME); sets.performXsltTransformation(); for (AbstractSet set : sets.getSets()) { createdFiles.add(set.getSetId()); } return createdFiles; }
00
Code Sample 1: private static String fetch(String urltxt, String cookie) { try { URL url = new URL(urltxt); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream source = url.openStream(); String data = new Scanner(source).useDelimiter("\\A").next(); Pattern p = Pattern.compile("form action=\"(.*)\" method=\"post\""); Matcher m = p.matcher(data); if (!m.find()) return ""; urltxt = m.group(1); url = new URL(urltxt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", cookie); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("dl.start=PREMIUM"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); while ((data = in.readLine()) != null) sb.append(data + System.getProperty("line.separator")); data = urltxt.substring(urltxt.lastIndexOf("/") + 1); p = Pattern.compile("<tr><td><a href=\"(.*?)" + data); m = p.matcher(sb.toString()); data = (m.find()) ? (m.group(1) + data + System.getProperty("line.separator")) : ""; return data; } catch (Exception e) { return ""; } } Code Sample 2: public void adjustPadding(File file, int paddingSize, long audioStart) throws FileNotFoundException, IOException { logger.finer("Need to move audio file to accomodate tag"); FileChannel fcIn = null; FileChannel fcOut; ByteBuffer paddingBuffer = ByteBuffer.wrap(new byte[paddingSize]); File paddedFile; try { paddedFile = File.createTempFile(Utils.getMinBaseFilenameAllowedForTempFile(file), ".new", file.getParentFile()); logger.finest("Created temp file:" + paddedFile.getName() + " for " + file.getName()); } catch (IOException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); if (ioe.getMessage().equals(FileSystemMessage.ACCESS_IS_DENIED.getMsg())) { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } else { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } } try { fcOut = new FileOutputStream(paddedFile).getChannel(); } catch (FileNotFoundException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToModifyFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } try { fcIn = new FileInputStream(file).getChannel(); long written = fcOut.write(paddingBuffer); logger.finer("Copying:" + (file.length() - audioStart) + "bytes"); long audiolength = file.length() - audioStart; if (audiolength <= MAXIMUM_WRITABLE_CHUNK_SIZE) { long written2 = fcIn.transferTo(audioStart, audiolength, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } else { long noOfChunks = audiolength / MAXIMUM_WRITABLE_CHUNK_SIZE; long lastChunkSize = audiolength % MAXIMUM_WRITABLE_CHUNK_SIZE; long written2 = 0; for (int i = 0; i < noOfChunks; i++) { written2 += fcIn.transferTo(audioStart + (i * MAXIMUM_WRITABLE_CHUNK_SIZE), MAXIMUM_WRITABLE_CHUNK_SIZE, fcOut); } written2 += fcIn.transferTo(audioStart + (noOfChunks * MAXIMUM_WRITABLE_CHUNK_SIZE), lastChunkSize, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } long lastModified = file.lastModified(); if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } replaceFile(file, paddedFile); paddedFile.setLastModified(lastModified); } finally { try { if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } } catch (Exception e) { logger.log(Level.WARNING, "Problem closing channels and locks:" + e.getMessage(), e); } } }
00
Code Sample 1: public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } } Code Sample 2: private static String simpleCompute(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("utf-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: public Constructor run() throws Exception { String path = "META-INF/services/" + ComponentApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = ComponentApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (ComponentApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new ComponentApplicationException("No " + "ComponentApplicationContext implementation " + "found."); } Code Sample 2: public static int[] sortDescending(int 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]) { int 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; }
00
Code Sample 1: protected long loadFromSource(long afterThisTime) { long startTime = System.currentTimeMillis(); QuoteDataSourceDescriptor quoteDataSourceDescriptor = (QuoteDataSourceDescriptor) dataSourceDescriptor; List<Quote> dataPool = dataPools.get(quoteDataSourceDescriptor.sourceSymbol); Calendar calendar = Calendar.getInstance(); calendar.clear(); SimpleDateFormat sdf = new SimpleDateFormat(quoteDataSourceDescriptor.dateFormat, Locale.US); Date fromDate = new Date(); Date toDate = new Date(); if (afterThisTime == FIRST_TIME_LOAD) { fromDate = quoteDataSourceDescriptor.fromDate; toDate = quoteDataSourceDescriptor.toDate; } else { calendar.setTimeInMillis(afterThisTime); fromDate = calendar.getTime(); } calendar.setTime(fromDate); int a = calendar.get(Calendar.MONTH); int b = calendar.get(Calendar.DAY_OF_MONTH); int c = calendar.get(Calendar.YEAR); calendar.setTime(toDate); int d = calendar.get(Calendar.MONTH); int e = calendar.get(Calendar.DAY_OF_MONTH); int f = calendar.get(Calendar.YEAR); BufferedReader dis; StringBuffer urlStr = new StringBuffer(); urlStr.append("http://table.finance.yahoo.com/table.csv").append("?s="); urlStr.append(quoteDataSourceDescriptor.sourceSymbol); urlStr.append("&a=" + a + "&b=" + b + "&c=" + c + "&d=" + d + "&e=" + e + "&f=" + f); urlStr.append("&g=d&ignore=.csv"); try { URL url = new URL(urlStr.toString()); System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(true); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(true); InputStreamReader isr = new InputStreamReader(conn.getInputStream()); dis = new BufferedReader(isr); String s = dis.readLine(); int iDateTime = 0; int iOpen = 1; int iHigh = 2; int iLow = 3; int iClose = 4; int iVolume = 5; int iAdjClose = 6; count = 0; calendar.clear(); while ((s = dis.readLine()) != null) { String[] items; items = s.split(","); if (items.length < 6) { break; } Date date = null; try { date = sdf.parse(items[iDateTime].trim()); } catch (ParseException ex) { ex.printStackTrace(); continue; } calendar.clear(); calendar.setTime(date); long time = calendar.getTimeInMillis(); if (time <= afterThisTime) { continue; } Quote quote = new Quote(); quote.time = time; quote.open = Float.parseFloat(items[iOpen].trim()); quote.high = Float.parseFloat(items[iHigh].trim()); quote.low = Float.parseFloat(items[iLow].trim()); quote.close = Float.parseFloat(items[iClose].trim()); quote.volume = Float.parseFloat(items[iVolume].trim()) / 100f; quote.amount = -1; quote.close_adj = Float.parseFloat(items[iAdjClose].trim()); if (quote.high * quote.low * quote.close == 0) { quote = null; continue; } dataPool.add(quote); if (count == 0) { firstTime = time; } lastTime = time; setAscending((lastTime >= firstTime) ? true : false); count++; } } catch (Exception ex) { System.out.println("Error in Reading File: " + ex.getMessage()); } long newestTime = (lastTime >= firstTime) ? lastTime : firstTime; return newestTime; } Code Sample 2: public static String generateHash(String value) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(value.getBytes()); } catch (NoSuchAlgorithmException e) { log.error("Could not find the requested hash method: " + e.getMessage()); } byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); }
00
Code Sample 1: public MytemMaster getMytemMaster(String janCode) throws GaeException { HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); BufferedReader reader = null; StringBuffer request = new StringBuffer(address); request.append("api/mytems/show?jan="); request.append(janCode); try { HttpGet httpGet = new HttpGet(request.toString()); HttpResponse httpResponse = client.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == NOT_FOUND) { return null; } if (statusCode >= 400) { throw new GaeException("Status Error = " + Integer.toString(statusCode)); } reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } return createMytemMaster(builder.toString()); } catch (ClientProtocolException e) { throw new GaeException(e); } catch (SocketTimeoutException e) { throw new GaeException(e); } catch (IOException exception) { throw new GaeException(exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: private void delay(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String url = request.getRequestURL().toString(); if (delayed.contains(url)) { delayed.remove(url); LOGGER.info(MessageFormat.format("Loading delayed resource at url = [{0}]", url)); chain.doFilter(request, response); } else { LOGGER.info("Returning resource = [LoaderApplication.swf]"); InputStream input = null; OutputStream output = null; try { input = getClass().getResourceAsStream("LoaderApplication.swf"); output = response.getOutputStream(); delayed.add(url); response.setHeader("Cache-Control", "no-cache"); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } }
00
Code Sample 1: public static void main(String args[]) { org.apache.xml.security.Init.init(); String signatureFileName = args[0]; javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); try { long start = System.currentTimeMillis(); org.apache.xml.security.Init.init(); File f = new File(signatureFileName); System.out.println("Verifying " + signatureFileName); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f)); VerifyExampleTest vf = new VerifyExampleTest(); vf.verify(doc); Constants.setSignatureSpecNSprefix("dsig"); Element sigElement = null; NodeList nodes = doc.getElementsByTagNameNS(org.apache.xml.security.utils.Constants.SignatureSpecNS, "Signature"); if (nodes.getLength() != 0) { System.out.println("Found " + nodes.getLength() + " Signature elements."); for (int i = 0; i < nodes.getLength(); i++) { sigElement = (Element) nodes.item(i); XMLSignature signature = new XMLSignature(sigElement, ""); KeyInfo ki = signature.getKeyInfo(); signature.addResourceResolver(new OfflineResolver()); if (ki != null) { if (ki.containsX509Data()) { System.out.println("Could find a X509Data element in the KeyInfo"); } KeyInfo kinfo = signature.getKeyInfo(); X509Certificate cert = null; if (kinfo.containsRetrievalMethod()) { RetrievalMethod m = kinfo.itemRetrievalMethod(0); URL url = new URL(m.getURI()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(url.openStream()); } else { cert = signature.getKeyInfo().getX509Certificate(); } if (cert != null) { System.out.println("The XML signature is " + (signature.checkSignatureValue(cert) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a Certificate"); PublicKey pk = signature.getKeyInfo().getPublicKey(); if (pk != null) { System.out.println("The XML signatur is " + (signature.checkSignatureValue(pk) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a public key, so I can't check the signature"); } } } else { System.out.println("Did not find a KeyInfo"); } } } long end = System.currentTimeMillis(); double elapsed = end - start; System.out.println("verified:" + elapsed); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
00
Code Sample 1: public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (XFile.class.isAssignableFrom(r.getClass())) { XFile file = (XFile) r; InputStream in = null; try { in = new XFileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } res.getOutputStream().flush(); } } Code Sample 2: public static String submitURLRequest(String url) throws HttpException, IOException, URISyntaxException { HttpClient httpclient = new DefaultHttpClient(); InputStream stream = null; user_agents = new LinkedList<String>(); user_agents.add("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); String response_text = ""; URI uri = new URI(url); HttpGet post = new HttpGet(uri); int MAX = user_agents.size() - 1; int index = (int) Math.round(((double) Math.random() * (MAX))); String agent = user_agents.get(index); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, agent); httpclient.getParams().setParameter("User-Agent", agent); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.ACCEPT_NONE); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { stream = entity.getContent(); response_text = convertStreamToString(stream); } httpclient.getConnectionManager().shutdown(); if (stream != null) { stream.close(); } return response_text; }
00
Code Sample 1: @Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static Document getDocument(URL url) throws Exception { InputStream is = null; try { is = new BufferedInputStream(url.openStream()); return getDocumentBuilder().parse(is); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } }
11
Code Sample 1: @SuppressWarnings("static-access") public FastCollection<String> load(Link link) { URL url = null; FastCollection<String> links = new FastList<String>(); FTPClient ftp = null; try { String address = link.getURI(); address = JGetFileUtils.removeTrailingString(address, "/"); url = new URL(address); host = url.getHost(); String folder = url.getPath(); logger.info("Traversing: " + address); ftp = new FTPClient(host); if (!ftp.connected()) { ftp.connect(); } ftp.login("anonymous", "me@mymail.com"); logger.info("Connected to " + host + "."); logger.debug("changing dir to " + folder); ftp.chdir(folder); String[] files = ftp.dir(); for (String file : files) { links.add(address + "/" + file); } } catch (Exception e) { logger.error(e.getMessage()); logger.debug(e.getStackTrace()); } finally { try { ftp.quit(); } catch (Exception e) { logger.error("Failed to logout or disconnect from the ftp server: ftp://" + host); } } return links; } Code Sample 2: public boolean login() { if (super.isAuthenticated()) return true; try { if (client == null) { client = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); client.configure(config); } if (!client.isConnected()) { client.connect(super.getStoreConfig().getServerName(), new Integer(super.getStoreConfig().getServerPort()).intValue()); } if (client.login(super.getStoreConfig().getUserName(), super.getStoreConfig().getPassword(), super.getStoreConfig().getServerName())) { super.setAuthenticated(true); return true; } log.error("Login ftp server error"); } catch (Exception e) { log.info("FTPStore.login", e); } return false; }
00
Code Sample 1: public void testExecute() throws Exception { LocalWorker worker = new JTidyWorker(); URL url = new URL("http://www.nature.com/index.html"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = in.readLine()) != null) { sb.append(str); sb.append(LINE_ENDING); } in.close(); Map inputMap = new HashMap(); DataThingAdapter inAdapter = new DataThingAdapter(inputMap); inAdapter.putString("inputHtml", sb.toString()); Map outputMap = worker.execute(inputMap); DataThingAdapter outAdapter = new DataThingAdapter(outputMap); assertNotNull("The outputMap was null", outputMap); String results = outAdapter.getString("results"); assertFalse("The results were empty", results.equals("")); assertNotNull("The results were null", results); } Code Sample 2: protected RemoteInputStream getUrlResource(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setConnectTimeout(url_loading_time_out); conn.setReadTimeout(url_loading_time_out); conn.setRequestProperty("connection", "Keep-Alive"); conn.connect(); long last_modify_time = conn.getLastModified(); IOCacheService cache_service = CIO.getAppBridge().getIO().getCache(); if (cache_service != null) { RemoteInputStream cache = cache_service.findCache(url, last_modify_time); if (cache != null) { return cache; } } return new URLConnectionInputStream(url, conn); }
00
Code Sample 1: public VeecheckResult performRequest(VeecheckVersion version, String uri) throws ClientProtocolException, IOException, IllegalStateException, SAXException { HttpClient client = new DefaultHttpClient(); HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT); HttpGet request = new HttpGet(version.substitute(uri)); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); try { StatusLine line = response.getStatusLine(); if (line.getStatusCode() != 200) throw new IOException("Request failed: " + line.getReasonPhrase()); Header header = response.getFirstHeader(HTTP.CONTENT_TYPE); Encoding encoding = identityEncoding(header); VeecheckResult handler = new VeecheckResult(version); Xml.parse(entity.getContent(), encoding, handler); return handler; } finally { entity.consumeContent(); } } 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 void read() throws LogicException { try { File file = new File(filename); URL url = file.toURI().toURL(); source = new Source(url.openConnection()); } catch (Exception e) { throw new LogicException("Failed to read " + filename + " !", e); } ArrayList<Segment> segments = new ArrayList<Segment>(); List<Element> elements = source.getChildElements(); for (Element element : elements) { Segment segment = element.getContent(); Iterator<Segment> iterator = segment.getNodeIterator(); while (iterator.hasNext()) { Segment current = iterator.next(); if (isPlainText(current)) { segments.add(current); } } } texts.clear(); sentences.clear(); for (int i = 0; i < segments.size(); i++) { ArrayList<Segment> group = new ArrayList<Segment>(); group.add(segments.get(i)); while (i < (segments.size() - 1) && segments.get(i).getEnd() == segments.get(i + 1).getBegin()) { group.add(segments.get(i + 1)); i++; } texts.add(new Text(group, tokenizer)); } ArrayList<Token> tokens = new ArrayList<Token>(); for (Text text : texts) { tokens.addAll(text.getTokens()); } sentences = tokenizer.toSentences(tokens); } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } }
11
Code Sample 1: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); } Code Sample 2: public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
11
Code Sample 1: public static void rewrite(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new FileInputStream(args[0])); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); CodeAttribute attribute = method.getCodeAttribute(); int origStack = attribute.getMaxStack(); System.out.print(method.getName()); attribute.codeCheck(); System.out.println(" " + origStack + " " + attribute.getMaxStack()); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } Code Sample 2: private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } }
11
Code Sample 1: public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); } Code Sample 2: public boolean validateLogin(String username, String password) { boolean user_exists = false; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); statement = connect.prepareStatement("SELECT id from toepen.users WHERE username = ? AND password = ?"); statement.setString(1, username); statement.setString(2, password_hash); resultSet = statement.executeQuery(); while (resultSet.next()) { user_exists = true; } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_exists; } }
00
Code Sample 1: public static String digest(String str) { StringBuffer sb = new StringBuffer(); try { MessageDigest md5 = MessageDigest.getInstance("md5"); md5.update(str.getBytes("ISO8859-1")); byte[] array = md5.digest(); for (int x = 0; x < 16; x++) { if ((array[x] & 0xff) < 0x10) sb.append("0"); sb.append(Long.toString(array[x] & 0xff, 16)); } } catch (Exception e) { System.out.println(e); } return sb.toString(); } Code Sample 2: public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
11
Code Sample 1: public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); } Code Sample 2: public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
00
Code Sample 1: @Override public int updateStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); return statement.executeUpdate(sql); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); return 0; } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } } Code Sample 2: public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } }
11
Code Sample 1: private static File copyJarToPool(File file) { File outFile = new File(RizzToolConstants.TOOL_POOL_FOLDER.getAbsolutePath() + File.separator + file.getName()); if (file != null && file.exists() && file.canRead()) { try { FileChannel inChan = new FileInputStream(file).getChannel(); FileChannel outChan = new FileOutputStream(outFile).getChannel(); inChan.transferTo(0, inChan.size(), outChan); return outFile; } catch (Exception ex) { RizzToolConstants.DEFAULT_LOGGER.error("Exception while copying jar file to tool pool [inFile=" + file.getAbsolutePath() + "] [outFile=" + outFile.getAbsolutePath() + ": " + ex); } } else { RizzToolConstants.DEFAULT_LOGGER.error("Could not copy jar file. File does not exist or can't read file. [inFile=" + file.getAbsolutePath() + "]"); } return null; } Code Sample 2: public static File extract(File source, String filename, File target) { if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null; boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1); try { Map contents = (Map) jarContents.get(source.getPath()); if (contents == null) { contents = new HashMap(); jarContents.put(source.getPath(), contents); ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; contents.put(zipEntry.getName(), zipEntry); } input.close(); } if (isDirectory) { Iterator it = contents.keySet().iterator(); while (it.hasNext()) { String next = (String) it.next(); if (next.startsWith(filename)) { ZipEntry zipEntry = (ZipEntry) contents.get(next); int n = filename.length(); File newTarget = new File(target, zipEntry.getName().substring(n)); extract(source, next, newTarget); } } return target; } ZipEntry entry = (ZipEntry) contents.get(filename); ZipFile input = new ZipFile(source); InputStream in = input.getInputStream(entry); target.getParentFile().mkdirs(); int bytesRead; byte[] buffer = new byte[1024]; FileOutputStream output = new FileOutputStream(target); while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.close(); return target; } catch (Exception ex) { ex.printStackTrace(); } return null; }
00
Code Sample 1: public static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } Code Sample 2: public static String stringToHash(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Should not happened: SHA-1 algorithm is missing."); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Should not happened: Could not encode text bytes '" + text + "' to iso-8859-1."); } return new String(Base64.encodeBase64(md.digest())); }
11
Code Sample 1: @Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.reset(); digest.update(((String) salt).getBytes("UTF-8")); String encodedRawPass = new String(digest.digest(rawPass.getBytes("UTF-8"))); return encodedRawPass.equals(encPass); } catch (Throwable e) { throw new DataAccessException("Error al codificar la contrase�a", e) { private static final long serialVersionUID = -302443565702455874L; }; } } Code Sample 2: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { URL url = new URL(upgradeURL); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); FileOutputStream out = new FileOutputStream(""); String bytes = ""; int data = buffIn.read(); int downloadedByteCount = 1; while (data != -1) { out.write(data); bytes.concat(Character.toString((char) data)); buffIn.read(); downloadedByteCount++; updateProgressBar(downloadedByteCount); } out.close(); buffIn.close(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(bytes.getBytes()); String hash = m.digest().toString(); if (hash.length() == 31) { hash = "0" + hash; } if (!hash.equalsIgnoreCase(md5Hash)) { } } catch (MalformedURLException e) { } catch (IOException io) { } catch (NoSuchAlgorithmException a) { } }
11
Code Sample 1: public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; } Code Sample 2: private void writeFile(File file, String fileName) { try { FileInputStream fin = new FileInputStream(file); FileOutputStream fout = new FileOutputStream(dirTableModel.getDirectory().getAbsolutePath() + File.separator + fileName); int val; while ((val = fin.read()) != -1) fout.write(val); fin.close(); fout.close(); dirTableModel.reset(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public final String encrypt(final String plaintext, final String salt) { if (plaintext == null) { throw new NullPointerException(); } if (salt == null) { throw new NullPointerException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update((plaintext + salt).getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } } Code Sample 2: public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
00
Code Sample 1: private final Vector<Class<?>> findSubclasses(URL location, String packageName, Class<?> superClass) { synchronized (results) { Map<Class<?>, URL> thisResult = new TreeMap<Class<?>, URL>(CLASS_COMPARATOR); Vector<Class<?>> v = new Vector<Class<?>>(); String fqcn = searchClass.getName(); List<URL> knownLocations = new ArrayList<URL>(); knownLocations.add(location); for (int loc = 0; loc < knownLocations.size(); loc++) { URL url = knownLocations.get(loc); File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Class<?> c = Class.forName(packageName + "." + classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(packageName + "." + classname)) { thisResult.put(c, url); } } catch (ClassNotFoundException cnfex) { if (debug) { errors.add(cnfex); } } catch (Exception ex) { if (debug) { errors.add(ex); } } catch (NoClassDefFoundError ncdfe) { if (debug) { errors.add(ncdfe); } } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jarFile = conn.getJarFile(); Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); String entryname = entry.getName(); if (!entry.isDirectory() && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Class c = Class.forName(classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(classname)) { thisResult.put(c, url); } } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (NoClassDefFoundError ncdfe) { errors.add(ncdfe); } catch (UnsatisfiedLinkError ule) { errors.add(ule); } catch (Exception exception) { errors.add(exception); } catch (Error error) { errors.add(error); } } } } catch (IOException ioex) { errors.add(ioex); } } } results.putAll(thisResult); Iterator<Class<?>> it = thisResult.keySet().iterator(); while (it.hasNext()) { v.add(it.next()); } return v; } } Code Sample 2: public synchronized void readModels(URL url, XmiExtensionParser xmiExtensionParser) throws OpenException { LOG.info("======================================="); LOG.info("== READING MODEL " + url); try { InputSource source = new InputSource(new XmiInputStream(url.openStream(), xmiExtensionParser, 100000, null)); source.setSystemId(url.toString()); readModels(source); } catch (IOException ex) { throw new OpenException(ex); } }
11
Code Sample 1: @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; } Code Sample 2: @Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } }
11
Code Sample 1: private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); } Code Sample 2: public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } }
11
Code Sample 1: public Image storeImage(String title, String pathToImage, Map<String, Object> additionalProperties) { File collectionFolder = ProjectManager.getInstance().getFolder(PropertyHandler.getInstance().getProperty("_default_collection_name")); File imageFile = new File(pathToImage); String filename = ""; String format = ""; File copiedImageFile; while (true) { filename = "image" + UUID.randomUUID().hashCode(); if (!DbEntryProvider.INSTANCE.idExists(filename)) { Path path = new Path(pathToImage); format = path.getFileExtension(); copiedImageFile = new File(collectionFolder.getAbsolutePath() + File.separator + filename + "." + format); if (!copiedImageFile.exists()) break; } } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(imageFile), 4096); out = new BufferedOutputStream(new FileOutputStream(copiedImageFile), 4096); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } Image image = new ImageImpl(); image.setId(filename); image.setFormat(format); image.setEntryDate(new Date()); image.setTitle(title); image.setAdditionalProperties(additionalProperties); boolean success = DbEntryProvider.INSTANCE.storeNewImage(image); if (success) return image; return null; } Code Sample 2: void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
11
Code Sample 1: public static boolean verify(String password, String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } byte[] data = Base64.decode(base64.toCharArray()); byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); } Code Sample 2: @Override public String encryptString(String passphrase, String message) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] bIn = cipher.doFinal(message.getBytes("UTF-8")); String base64Encoded = base64encode(bIn); return base64Encoded; }
11
Code Sample 1: @Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (beforeServingFile(req, resp)) { String pathInfo = req.getPathInfo(); Validate.notNull(pathInfo, "the path info is null -> the sevlet should be mapped with /<mapping>/*"); String resurouce = pathInfo.substring(1); if (log.isDebugEnabled()) { log.debug("resource to expose: " + resurouce); } String extension = resurouce.substring(resurouce.lastIndexOf('.') + 1); MimeType mimeType = MimeTypeRegistry.getByExtension(extension); Validate.notNull(mimeType, "no mimetype found for extension: " + extension); if (log.isDebugEnabled()) { log.debug("the mime type to set: " + mimeType.getMimeType()); } File f = new File(mappedFolder, resurouce); Validate.isTrue(f.exists(), "file: " + f + " does not exist"); Validate.isTrue(f.canRead(), "can not read the file: " + f); if (log.isDebugEnabled()) { log.debug("exposing the file: " + f); } resp.setContentType(mimeType.getMimeType()); FileInputStream fis = new FileInputStream(f); ServletOutputStream os = resp.getOutputStream(); IOUtils.copy(fis, os); os.flush(); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(os); } } Code Sample 2: public static void copy(File from, File to) { if (from.getAbsolutePath().equals(to.getAbsolutePath())) { return; } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(from); os = new FileOutputStream(to); int read = -1; byte[] buffer = new byte[10000]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } catch (Exception e) { throw new RuntimeException(); } finally { try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public void writeBack(File destinationFile, boolean makeCopy) throws IOException { if (makeCopy) { FileChannel sourceChannel = new java.io.FileInputStream(getFile()).getChannel(); FileChannel destinationChannel = new java.io.FileOutputStream(destinationFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } else { getFile().renameTo(destinationFile); } if (getExifTime() != null && getOriginalTime() != null && !getExifTime().equals(getOriginalTime())) { String adjustArgument = "-ts" + m_dfJhead.format(getExifTime()); ProcessBuilder pb = new ProcessBuilder(m_tm.getJheadCommand(), adjustArgument, destinationFile.getAbsolutePath()); pb.directory(destinationFile.getParentFile()); System.out.println(pb.command().get(0) + " " + pb.command().get(1) + " " + pb.command().get(2)); final Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } }
11
Code Sample 1: private String encryptUserPassword(int userId, String password) { password = password.trim(); if (password.length() == 0) { return ""; } else { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw new BoardRuntimeException(ex); } md.update(String.valueOf(userId).getBytes()); md.update(password.getBytes()); byte b[] = md.digest(); StringBuffer sb = new StringBuffer(1 + b.length * 2); for (int i = 0; i < b.length; i++) { int ii = b[i]; if (ii < 0) { ii = 256 + ii; } sb.append(getHexadecimalValue2(ii)); } return sb.toString(); } } Code Sample 2: public static byte[] encode(String origin, String algorithm) throws NoSuchAlgorithmException { String resultStr = null; resultStr = new String(origin); MessageDigest md = MessageDigest.getInstance(algorithm); md.update(resultStr.getBytes()); return md.digest(); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: 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 void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } } Code Sample 2: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; }
11
Code Sample 1: public static void copyFile(File oldPathFile, File newPathFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(oldPathFile)); out = new BufferedOutputStream(new FileOutputStream(newPathFile)); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (in.read(buffer) > 0) out.write(buffer); } finally { if (null != in) in.close(); if (null != out) out.close(); } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { log.debug("Copying file: '" + src + "' to '" + dest + "'"); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }