label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
private static void generateTIFF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException { Debug.println("ImageCropper.generateTIFF begin"); MapContext map_context = new MapContext("test", new Configuration()); try { Map map = new Map(map_context, area_label, new Configuration()); map.setCoordSys(ProjectionCategories.default_coordinate_system); map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white))); String type = null; RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename)); map.addLayer(rlayer, true); map.setBounds2DImage(bounds, true); Dimension image_dim = null; image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1); if (output_maximum_size > 0) { double width_factor = image_dim.getWidth() / output_maximum_size; double height_factor = image_dim.getHeight() / output_maximum_size; double factor = Math.max(width_factor, height_factor); if (factor > 1.0) { image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor); } } map.setImageDimension(image_dim); map.scale(); image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight()); Image image = null; Graphics gr = null; image = ImageCreator.getImage(image_dim); gr = image.getGraphics(); try { map.paint(gr); } catch (Exception e) { Debug.println("map.paint error: " + e.getMessage()); } String tiff_filename = ""; try { tiff_filename = formatPath(category, timeseries, output_filename); new File(new_filename).mkdirs(); Debug.println("tiff_filename: " + tiff_filename); BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED); bi.createGraphics().drawImage(image, 0, 0, null); File f = new File(tiff_filename); FileOutputStream out = new FileOutputStream(f); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS); TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param); encoder.encode(bi); out.close(); } catch (IOException e) { Debug.println("ImageCropper.generateTIFF TIFFCodec e: " + e.getMessage()); throw new IOException("GenerateTIFF.IOException: " + e); } PreparedStatement pstmt = null; try { String query = "select Proj_ID, AccessType_Code from project " + "where Proj_Code= '" + area_code.trim() + "'"; Statement stmt = null; ResultSet rs = null; int proj_id = -1; int access_code = -1; stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { proj_id = rs.getInt(1); access_code = rs.getInt(2); } rs.close(); stmt.close(); String delete_raster = "delete from rasterlayer where " + "Raster_Name='" + tiff_name.trim() + "' and Group_Code='" + category.trim() + "' and Proj_ID =" + proj_id; Debug.println("***** delete_raster: " + delete_raster); pstmt = con.prepareStatement(delete_raster); boolean del = pstmt.execute(); pstmt.close(); String insert_raster = "insert into rasterlayer(Raster_Name, " + "Group_Code, Proj_ID, Raster_TimeCode, Raster_Xmin, " + "Raster_Ymin, Raster_Area_Xmin, Raster_Area_Ymin, " + "Raster_Visibility, Raster_Order, Raster_Path, " + "AccessType_Code, Raster_TimePeriod) values(?,?,?,?, " + "?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(insert_raster); pstmt.setString(1, tiff_name); pstmt.setString(2, category); pstmt.setInt(3, proj_id); pstmt.setString(4, timeseries); pstmt.setDouble(5, raster_bounds.getX()); pstmt.setDouble(6, raster_bounds.getY()); pstmt.setDouble(7, raster_bounds.getWidth()); pstmt.setDouble(8, raster_bounds.getHeight()); pstmt.setString(9, "false"); int sequence = 0; if (tiff_name.endsWith("DP")) { sequence = 1; } else if (tiff_name.endsWith("DY")) { sequence = 2; } else if (tiff_name.endsWith("DA")) { sequence = 3; } pstmt.setInt(10, sequence); pstmt.setString(11, tiff_filename); pstmt.setInt(12, access_code); if (time == null) { pstmt.setNull(13, java.sql.Types.DATE); } else { pstmt.setDate(13, new java.sql.Date(time.getTimeInMillis())); } pstmt.executeUpdate(); } catch (SQLException e) { Debug.println("SQLException occurred e: " + e.getMessage()); con.rollback(); throw new SQLException("GenerateTIFF.SQLException: " + e); } finally { pstmt.close(); } } catch (Exception e) { Debug.println("ImageCropper.generateTIFF e: " + e.getMessage()); } Debug.println("ImageCropper.generateTIFF end"); }
Code Sample 2:
public static synchronized String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new BASE64Encoder().encode(raw); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage()); } }
|
00
|
Code Sample 1:
public String calculateDigest(String str) { StringBuffer s = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); for (byte d : digest) { s.append(Integer.toHexString((int) (d & 0xff))); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return s.toString(); }
Code Sample 2:
protected ResourceBundle loadBundle(String prefix) { URL url = Thread.currentThread().getContextClassLoader().getResource(prefix + ".properties"); if (url != null) { try { return new PropertyResourceBundle(url.openStream()); } catch (IOException e) { throw ThrowableManagerRegistry.caught(e); } } return null; }
|
00
|
Code Sample 1:
private InputStream classpathStream(String path) { InputStream in = null; URL url = getClass().getClassLoader().getResource(path); if (url != null) { try { in = url.openStream(); } catch (IOException e) { e.printStackTrace(); } } return in; }
Code Sample 2:
public Reader transform(Reader reader, Map<String, Object> parameterMap) { try { File file = File.createTempFile("srx2", ".srx"); file.deleteOnExit(); Writer writer = getWriter(getFileOutputStream(file.getAbsolutePath())); transform(reader, writer, parameterMap); writer.close(); Reader resultReader = getReader(getFileInputStream(file.getAbsolutePath())); return resultReader; } catch (IOException e) { throw new IORuntimeException(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 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) { } } }
|
00
|
Code Sample 1:
void copyFile(File src, File dst) throws IOException { FileInputStream fis = new FileInputStream(src); byte[] buf = new byte[10000]; int n; FileOutputStream fos = new FileOutputStream(dst); while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); copied++; }
Code Sample 2:
protected IStatus run(IProgressMonitor monitor) { try { updateRunning = true; distributor = getFromFile("[SERVER]", "csz", getAppPath() + "/server.ini"); MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); if (MAC.equals("not_found") || serial.equals("not_found") || !serial.startsWith(distributor)) { try { MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); } catch (Exception e) { System.out.println(e); } } else { try { url = new URL("http://" + getFromFile("[SERVER]", "url", getAppPath() + "/server.ini")); } catch (MalformedURLException e) { System.out.println(e); } download = "/download2.php?distributor=" + distributor + "&&mac=" + MAC + "&&serial=" + serial; readXML(); if (htmlMessage.contains("error")) { try { PrintWriter pw = new PrintWriter(getAppPath() + "/register.ini"); pw.write(""); pw.close(); } catch (IOException e) { System.out.println(e); } setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } } else { if (!getDBVersion().equals(latestVersion)) { try { OutputStream out = null; HttpURLConnection conn = null; InputStream in = null; int size; try { URL url = new URL(fileLoc); String outFile = getAppPath() + "/temp/" + getFileName(url); File oFile = new File(outFile); oFile.delete(); out = new BufferedOutputStream(new FileOutputStream(outFile)); monitor.beginTask("Connecting to NWD Server", 100); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20000); conn.connect(); if (conn.getResponseCode() / 100 != 2) { System.out.println("Error: " + conn.getResponseCode()); return null; } monitor.worked(100); monitor.done(); size = conn.getContentLength(); monitor.beginTask("Download Worm Definition", size); in = conn.getInputStream(); byte[] buffer; String downloadedSize; long numWritten = 0; boolean status = true; while (status) { if (size - numWritten > 1024) { buffer = new byte[1024]; } else { buffer = new byte[(int) (size - numWritten)]; } int read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); numWritten += read; downloadedSize = Long.toString(numWritten / 1024) + " KB"; monitor.worked(read); monitor.subTask(downloadedSize + " of " + Integer.toString(size / 1024) + " KB"); if (size == numWritten) { status = false; } if (monitor.isCanceled()) return Status.CANCEL_STATUS; } if (in != null) { in.close(); } if (out != null) { out.close(); } try { ZipFile zFile = new ZipFile(outFile); Enumeration all = zFile.entries(); while (all.hasMoreElements()) { ZipEntry zEntry = (ZipEntry) all.nextElement(); long zSize = zEntry.getSize(); if (zSize > 0) { if (zEntry.getName().endsWith("script")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[0]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } else if (zEntry.getName().endsWith("data")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[1]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } } } File xFile = new File(outFile); xFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } try { monitor.done(); monitor.beginTask("Install Worm Definition", 10000); monitor.worked(2500); CorePlugin.getDefault().getRawPacketHandler().removeRawPacketListener(p); p = null; if (!wormDB.getConn().isClosed()) { shutdownDB(); } System.out.println(wormDB.getConn().isClosed()); for (int i = 0; i < 2; i++) { try { Process pid = Runtime.getRuntime().exec("cmd /c copy \"" + oldLoc[i].replace("/", "\\") + "\" \"" + newLoc[i].replace("/", "\\") + "\"/y"); } catch (Exception e) { e.printStackTrace(); } new File(oldLoc[i]).deleteOnExit(); } monitor.worked(2500); initialArray(); p = new PacketPrinter(); CorePlugin.getDefault().getRawPacketHandler().addRawPacketListener(p); monitor.worked(2500); monitor.done(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction()); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } System.out.println(e); } finally { } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } e.printStackTrace(); } } else { cancel(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults1(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction1()); } } } } return Status.OK_STATUS; } catch (Exception e) { showResults2(); return Status.OK_STATUS; } finally { lock.release(); updateRunning = false; if (getValue("AUTO_UPDATE")) schedule(10800000); } }
|
00
|
Code Sample 1:
Object onSuccess() { this.mErrorExist = true; this.mErrorMdp = true; if (this.mNewMail.equals(mClient.getEmail()) || !this.mNewMail.equals(mClient.getEmail()) && !mClientManager.exists(this.mNewMail)) { this.mErrorExist = false; if (mNewMdp != null && mNewMdpConfirm != null) { if (this.mNewMdp.equals(this.mNewMdpConfirm)) { this.mErrorMdp = false; MessageDigest sha1Instance; try { sha1Instance = MessageDigest.getInstance("SHA1"); sha1Instance.reset(); sha1Instance.update(this.mNewMdp.getBytes()); byte[] digest = sha1Instance.digest(); BigInteger bigInt = new BigInteger(1, digest); String vHashPassword = bigInt.toString(16); mClient.setMdp(vHashPassword); } catch (NoSuchAlgorithmException e) { mLogger.error(e.getMessage(), e); } } } else { this.mErrorMdp = false; } if (!this.mErrorMdp) { mClient.setAdresse(this.mNewAdresse); mClient.setEmail(this.mNewMail); mClient.setNom(this.mNewNom); mClient.setPrenom((this.mNewPrenom != null ? this.mNewPrenom : "")); Client vClient = new Client(mClient); mClientManager.save(vClient); mComponentResources.discardPersistentFieldChanges(); return "Client/List"; } } return errorZone.getBody(); }
Code Sample 2:
public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
|
11
|
Code Sample 1:
public static boolean update(ItemNotaFiscal objINF) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; CelulaFinanceira objCF = null; if (c == null) { return false; } if (objINF == null) { return false; } try { c.setAutoCommit(false); String sql = ""; sql = "update item_nota_fiscal " + "set id_item_pedido = ? " + "where id_item_nota_fiscal = ?"; pst = c.prepareStatement(sql); pst.setInt(1, objINF.getItemPedido().getCodigo()); pst.setInt(2, objINF.getCodigo()); result = pst.executeUpdate(); if (result > 0) { if (objINF.getItemPedido().getCelulaFinanceira() != null) { objCF = objINF.getItemPedido().getCelulaFinanceira(); objCF.atualizaGastoReal(objINF.getSubtotal()); if (CelulaFinanceiraDAO.update(objCF)) { } } } c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[ItemNotaFiscalDAO.update.rollback] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[ItemNotaFiscalDAO.update.insert] Erro ao inserir -> " + e.getMessage()); result = 0; } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
private int renumberOrderBy(long tableID) throws SnapInException { int count = 0; Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = getDataSource().getConnection(); con.setAutoCommit(false); stmt = con.createStatement(); StringBuffer query = new StringBuffer(); query.append("SELECT ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" FROM ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_TABLEID).append(" = ").append(tableID).append(" ORDER BY ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY); Vector rowIDVector = new Vector(); rs = stmt.executeQuery(query.toString()); while (rs.next()) { count++; rowIDVector.add(rs.getLong(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID) + ""); } StringBuffer updateString = new StringBuffer(); updateString.append("UPDATE ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" SET ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY).append(" = ? WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" = ?"); PreparedStatement pstmt = con.prepareStatement(updateString.toString()); int orderByValue = ORDERBY_BY_DELTA_VALUE; Enumeration en = rowIDVector.elements(); while (en.hasMoreElements()) { pstmt.setInt(1, orderByValue); pstmt.setString(2, en.nextElement().toString()); orderByValue += ORDERBY_BY_DELTA_VALUE; pstmt.executeUpdate(); } con.setAutoCommit(true); if (pstmt != null) { pstmt.close(); } } catch (java.sql.SQLException e) { if (con == null) { logger.error("java.sql.SQLException", e); } else { try { logger.error("Transaction is being rolled back."); con.rollback(); con.setAutoCommit(true); } catch (java.sql.SQLException e2) { logger.error("java.sql.SQLException", e2); } } } catch (Exception e) { logger.error("Error occured during RenumberOrderBy", e); } finally { getDataSourceHelper().releaseResources(con, stmt, rs); } return count; }
|
00
|
Code Sample 1:
public static String hash(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); byte[] digest = md.digest(); StringBuffer sb = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; ++i) { byte b = digest[i]; int high = (b & 0xF0) >> 4; int low = b & 0xF; sb.append(DECIMAL_HEX[high]); sb.append(DECIMAL_HEX[low]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new NonBusinessException("Error hashing string", e); } }
Code Sample 2:
public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } }
|
00
|
Code Sample 1:
private void copyFile(File dir, File fileToAdd) { try { byte[] readBuffer = new byte[1024]; File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName()); if (file.createNewFile()) { FileInputStream fis = new FileInputStream(fileToAdd); FileOutputStream fos = new FileOutputStream(file); int bytesRead; do { bytesRead = fis.read(readBuffer); fos.write(readBuffer, 0, bytesRead); } while (bytesRead == 0); fos.flush(); fos.close(); fis.close(); } else { logger.severe("unable to create file:" + file.getAbsolutePath()); } } catch (IOException ioe) { logger.severe("unable to create file:" + ioe); } }
Code Sample 2:
public String generateDigest(String password, String saltHex, String algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsIgnoreCase("crypt")) { return "{CRYPT}" + UnixCrypt.crypt(password); } else if (algorithm.equalsIgnoreCase("sha")) { algorithm = "SHA-1"; } else if (algorithm.equalsIgnoreCase("md5")) { algorithm = "MD5"; } MessageDigest msgDigest = MessageDigest.getInstance(algorithm); byte[] salt = {}; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (algorithm.startsWith("SHA")) { label = (salt.length > 0) ? "{SSHA}" : "{SHA}"; } else if (algorithm.startsWith("MD5")) { label = (salt.length > 0) ? "{SMD5}" : "{MD5}"; } msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt))); return digest.toString(); }
|
11
|
Code Sample 1:
public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
Code Sample 2:
public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } }
|
11
|
Code Sample 1:
public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
00
|
Code Sample 1:
public static String sendRequest(String urlstring) { URL url; String line; Log.i("DVBMonitor", "Please wait while receiving data from dvb..."); try { url = new URL(urlstring); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); if ((line = in.readLine()) != null) { return line; } else { return null; } } catch (Exception ex) { Log.e("DVBMonitor", ex.toString() + " while sending request to dvb"); return null; } }
Code Sample 2:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
|
11
|
Code Sample 1:
private void handleSSI(HttpData data) throws HttpError, IOException { File tempFile = TempFileHandler.getTempFile(); FileOutputStream out = new FileOutputStream(tempFile); BufferedReader in = new BufferedReader(new FileReader(data.realPath)); String[] env = getEnvironmentVariables(data); if (ssi == null) { ssi = new BSssi(); } ssi.addEnvironment(env); if (data.resp == null) { SimpleResponse resp = new SimpleResponse(); resp.setHeader("Content-Type", "text/html"); moreHeaders(resp); resp.setHeader("Connection", "close"); data.resp = resp; resp.write(data.out); } String t; int start; Enumeration en; boolean anIfCondition = true; while ((t = in.readLine()) != null) { if ((start = t.indexOf("<!--#")) > -1) { if (anIfCondition) out.write(t.substring(0, start).getBytes()); try { en = ssi.parse(t.substring(start)).elements(); SSICommand command; while (en.hasMoreElements()) { command = (SSICommand) en.nextElement(); logger.fine("Command=" + command); switch(command.getCommand()) { case BSssi.CMD_IF_TRUE: anIfCondition = true; break; case BSssi.CMD_IF_FALSE: anIfCondition = false; break; case BSssi.CMD_CGI: out.flush(); if (command.getFileType() != null && command.getFileType().startsWith("shtm")) { HttpData d = newHttpData(data); d.out = out; d.realPath = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()); new SsiHandler(d, ssi).perform(); } else { String application = getExtension(command.getFileType()); if (application == null) { writePaused(new FileInputStream(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())), out, pause); } else { String parameter = ""; if (command.getMessage().indexOf("php") >= 0) { parameter = "-f "; } Process p = Runtime.getRuntime().exec(application + " " + parameter + HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); } } break; case BSssi.CMD_EXEC: Process p = Runtime.getRuntime().exec(command.getMessage()); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); BufferedReader pErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((aLine = pErr.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); pErr.close(); p.destroy(); break; case BSssi.CMD_INCLUDE: File incFile = HttpThread.getMappedFilename(command.getMessage()); if (incFile.exists() && incFile.canRead()) { writePaused(new FileInputStream(incFile), out, pause); } break; case BSssi.CMD_FILESIZE: long sizeBytes = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).length(); double smartSize; String unit = "bytes"; if (command.getFileType().trim().equals("abbrev")) { if (sizeBytes > 1000000) { smartSize = sizeBytes / 1024000.0; unit = "M"; } else if (sizeBytes > 1000) { smartSize = sizeBytes / 1024.0; unit = "K"; } else { smartSize = sizeBytes; unit = "bytes"; } NumberFormat numberFormat = new DecimalFormat("#,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(smartSize) + "" + unit).getBytes()); } else { NumberFormat numberFormat = new DecimalFormat("#,###,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(sizeBytes) + " " + unit).getBytes()); } break; case BSssi.CMD_FLASTMOD: out.write(ssi.format(new Date(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).lastModified()), TimeZone.getTimeZone("GMT")).getBytes()); break; case BSssi.CMD_NOECHO: break; case BSssi.CMD_ECHO: default: out.write(command.getMessage().getBytes()); break; } } } catch (Exception e) { e.printStackTrace(); out.write((ssi.getErrorMessage() + " " + e.getMessage()).getBytes()); } if (anIfCondition) out.write("\n".getBytes()); } else { if (anIfCondition) out.write((t + "\n").getBytes()); } out.flush(); } in.close(); out.close(); data.fileData.setContentType("text/html"); data.fileData.setFile(tempFile); writePaused(new FileInputStream(tempFile), data.out, pause); logger.fine("HandleSSI done for " + data.resp); }
Code Sample 2:
private static void processFile(StreamDriver driver, String sourceName) throws Exception { String destName = sourceName + ".xml"; File dest = new File(destName); if (dest.exists()) { throw new IllegalArgumentException("File '" + destName + "' already exists!"); } FileChannel sourceChannel = new FileInputStream(sourceName).getChannel(); try { MappedByteBuffer sourceByteBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, 0, sourceChannel.size()); CharsetDecoder decoder = Charset.forName("ISO-8859-15").newDecoder(); CharBuffer sourceBuffer = decoder.decode(sourceByteBuffer); driver.generateXmlDocument(sourceBuffer, new FileOutputStream(dest)); } finally { sourceChannel.close(); } }
|
00
|
Code Sample 1:
public String hasheMotDePasse(String mdp) { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { } sha.reset(); sha.update(mdp.getBytes()); byte[] digest = sha.digest(); String pass = new String(Base64.encode(digest)); pass = "{SHA}" + pass; return pass; }
Code Sample 2:
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; for (JarFile java3DJar : this.java3DJars) { JarEntry jarEntry = java3DJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = java3DJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } }
|
00
|
Code Sample 1:
@Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } }
Code Sample 2:
private String encryptPassword(String password) throws NoSuchAlgorithmException { MessageDigest encript = MessageDigest.getInstance("MD5"); encript.update(password.getBytes()); byte[] b = encript.digest(); int size = b.length; StringBuffer h = new StringBuffer(size); for (int i = 0; i < size; i++) { h.append(b[i]); } return h.toString(); }
|
00
|
Code Sample 1:
protected static URL[] createUrls(URL jarUrls[]) { ArrayList<URL> additionalUrls = new ArrayList<URL>(Arrays.asList(jarUrls)); for (URL ju : jarUrls) { try { JarFile jar = new JarFile(ju.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (j.isDirectory()) continue; if (j.getName().startsWith("lib/") && j.getName().endsWith(".jar")) { URL url = new URL("jar:" + ju.getProtocol() + ":" + ju.getFile() + "!/" + j.getName()); InputStream is = url.openStream(); File tmpFile = File.createTempFile("SCDeploy", ".jar"); FileOutputStream fos = new FileOutputStream(tmpFile); IOUtils.copy(is, fos); is.close(); fos.close(); additionalUrls.add(new URL("file://" + tmpFile.getAbsolutePath())); } } } catch (IOException e) { } } return additionalUrls.toArray(new URL[] {}); }
Code Sample 2:
private void onOKAction() { if (url == null) { optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); JOptionPane.showMessageDialog(this, "URL field cannot be empty", "Empty URL", JOptionPane.ERROR_MESSAGE); } else { try { URLConnection sourceConnection = url.openConnection(); sourceConnection.setConnectTimeout(10); if (sourceConnection.getContentLength() == -1) { throw new IOException("Can't connect to " + url.toString()); } exit_status = OK; setVisible(false); dispose(); } catch (IOException e) { optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); JOptionPane.showMessageDialog(this, "Please enter valid, resolvable source and target URLs...\n " + e.getMessage(), "Invalid URL", JOptionPane.ERROR_MESSAGE); } } }
|
11
|
Code Sample 1:
public static String httpGet(URL url) throws Exception { URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); }
Code Sample 2:
public String get(String s, String encoding) throws Exception { if (!s.startsWith("http")) return ""; StringBuilder sb = new StringBuilder(); try { String result = null; URL url = new URL(s); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); if (encoding == null) encoding = "UTF-8"; BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); String inputLine; String contentType = connection.getContentType(); if (contentType.startsWith("text") || contentType.startsWith("application/xml")) { while ((inputLine = in.readLine()) != null) { sb.append(inputLine); sb.append("\n"); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw e; } return sb.toString(); }
|
11
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } }
Code Sample 2:
public void add(final String name, final String content) { forBundle(new BundleManipulator() { public boolean includeEntry(String entryName) { return !name.equals(entryName); } public void finish(Bundle bundle, ZipOutputStream zout) throws IOException { zout.putNextEntry(new ZipEntry(name)); IOUtils.copy(new StringReader(content), zout, "UTF-8"); } }); }
|
11
|
Code Sample 1:
public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8, 24); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public static String encodePassword(String password, byte[] seed) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (seed == null) { seed = new byte[12]; secureRandom.nextBytes(seed); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(seed, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new sun.misc.BASE64Encoder().encode(storedPassword); }
|
00
|
Code Sample 1:
public static String getHash(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(password.getBytes()); return new String(digest.digest()); } catch (NoSuchAlgorithmException e) { log.error("Hashing algorithm not found"); return password; } }
Code Sample 2:
private boolean postCorrecao() { boolean valido = false; Integer newCodCorrecao = null; String sqlmaxac = "SELECT MAX(SEQAC) FROM PPOPACAOCORRET WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; String sqlmaxcq = "SELECT MAX(SEQOPCQ) + 1 FROM PPOPCQ WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; try { for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { valido = true; keysItens[2] = ek.getKey(); break; } } if (!valido) { Funcoes.mensagemInforma(this, "Selecione as analises para aplicar a corre��o!"); return false; } if (txaCausa.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Informe as causas!"); return false; } if (txaAcao.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Detalhe a a��o corretiva!"); return false; } PreparedStatement ps = con.prepareStatement(sqlmaxac); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ResultSet rs = ps.executeQuery(); if (rs.next()) { newCodCorrecao = rs.getInt(1) + 1; keysItens[3] = newCodCorrecao; } rs.close(); ps.close(); if (newCodCorrecao != null) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO PPOPACAOCORRET "); sql.append("( CODEMP, CODFILIAL, CODOP, SEQOP, SEQAC, TPCAUSA, OBSCAUSA, TPACAO, OBSACAO ) "); sql.append("VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, newCodCorrecao); ps.setString(6, m.getCode()); ps.setString(7, txaCausa.getVlrString()); ps.setString(8, rgSolucao.getVlrString()); ps.setString(9, txaAcao.getVlrString()); ps.execute(); ps.close(); String strAnalises = ""; for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { if (strAnalises.trim().length() > 0) { strAnalises += ","; } strAnalises += String.valueOf(ek.getKey()); } } sql = new StringBuilder(); sql.append("UPDATE PPOPCQ SET SEQAC=? "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, newCodCorrecao); ps.setInt(2, Aplicativo.iCodEmp); ps.setInt(3, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(4, txtCodOP.getVlrInteger()); ps.setInt(5, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); sql.delete(0, sql.length()); sql.append("INSERT INTO PPOPCQ (CODEMP,CODFILIAL,CODOP,SEQOP,SEQOPCQ,"); sql.append("CODEMPEA,CODFILIALEA,CODESTANALISE) "); sql.append("SELECT CODEMP,CODFILIAL,CODOP,SEQOP,("); sql.append(sqlmaxcq); sql.append("),CODEMPEA,CODFILIALEA,CODESTANALISE "); sql.append("FROM PPOPCQ "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND "); sql.append("SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); System.out.println(sql.toString()); ps = con.prepareStatement(sql.toString()); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(7, txtCodOP.getVlrInteger()); ps.setInt(8, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); montaAnalises(); Funcoes.mensagemInforma(this, "A��o corretiva aplicada com sucesso!"); } con.commit(); } catch (Exception err) { try { con.rollback(); } catch (SQLException e) { System.out.println("Erro ao realizar rollback!\n" + err.getMessage()); } err.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao atualizar analises!\n" + err.getMessage(), true, con, err); valido = false; } return valido; }
|
00
|
Code Sample 1:
public static String encrypt(String text) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String result = ""; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes()); byte[] hash = digest.digest(); char buffer[] = new char[hash.length * 2]; for (int i = 0, x = 0; i < hash.length; i++) { buffer[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; buffer[x++] = HEX_CHARS[hash[i] & 0xf]; } result = new String(buffer); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
Code Sample 2:
private boolean loadSymbol(QuoteCache quoteCache, Symbol symbol, TradingDate startDate, TradingDate endDate) { boolean success = true; String URLString = constructURL(symbol, startDate, endDate); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url; url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; while ((line = bufferedInput.readLine()) != null) { Class cl = null; Constructor cnst = null; QuoteFilter filter = null; try { cl = Class.forName("org.mov.quote." + name + "QuoteFilter"); try { cnst = cl.getConstructor(new Class[] { Symbol.class }); } catch (SecurityException e2) { e2.printStackTrace(); } catch (NoSuchMethodException e2) { e2.printStackTrace(); } try { filter = (QuoteFilter) cnst.newInstance(new Object[] { symbol }); } catch (IllegalArgumentException e3) { e3.printStackTrace(); } catch (InstantiationException e3) { e3.printStackTrace(); } catch (IllegalAccessException e3) { e3.printStackTrace(); } catch (InvocationTargetException e3) { e3.printStackTrace(); } } catch (ClassNotFoundException e1) { e1.printStackTrace(); } Quote quote = filter.toQuote(line); if (quote != null) quoteCache.load(quote); } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); success = false; } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); success = false; } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); success = false; } catch (FileNotFoundException e) { } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); success = false; } return success; }
|
11
|
Code Sample 1:
public boolean loadResource(String resourcePath) { try { URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (url == null) { logger.error("Cannot find the resource named: '" + resourcePath + "'. Failed to load the keyword list."); return false; } InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ligne = br.readLine(); while (ligne != null) { if (!contains(ligne.toUpperCase())) { addLast(ligne.toUpperCase()); } ligne = br.readLine(); } return true; } catch (IOException ioe) { logger.log(Level.ERROR, "Cannot load default SQL keywords file.", ioe); } return false; }
Code Sample 2:
private String callPage(String urlStr) throws IOException { URL url = new URL(urlStr); BufferedReader reader = null; StringBuilder result = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } } finally { if (reader != null) reader.close(); } return result.toString(); }
|
11
|
Code Sample 1:
public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; }
Code Sample 2:
private boolean checkTimestamp(File timestamp, URL url) { try { if (timestamp.exists()) { FileReader reader = null; Date dateLocal = null; try { reader = new FileReader(timestamp); StringWriter tmp = new StringWriter(); IOUtils.copy(reader, tmp); dateLocal = this.FORMAT.parse(tmp.toString()); } catch (ParseException e) { timestamp.delete(); } catch (IOException e) { } finally { IOUtils.closeQuietly(reader); } if (dateLocal != null) { try { URLConnection conn = url.openConnection(); Date date = this.FORMAT.parse(this.FORMAT.format(new Date(conn.getLastModified()))); return (date.compareTo(dateLocal) == 0); } catch (IOException e) { } } } } catch (Throwable t) { } return false; }
|
00
|
Code Sample 1:
private String readAboutText(String urlStr) { String text = null; try { URL url = this.getClass().getResource(urlStr); InputStreamReader reader = new InputStreamReader(url.openStream()); StringWriter writer = new StringWriter(); int character = reader.read(); while (character != -1) { writer.write(character); character = reader.read(); } text = writer.toString(); } catch (IOException e) { e.printStackTrace(); text = "<html><body><b>Author:</b><br>" + aAuthor + "<br>"; text += "<a href=\"mailto:jhuwaldt@mac.com\">jhuwaldt@mac.com</a><br>"; text += "<P ALIGN=CENTER><BR>" + aName + " comes with ABSOLUTELY NO WARRANTY;"; text += "<BR>This is free software, and you are welcome to redistribute "; text += "it and it's source code under certain conditions."; text += "<BR>Source code is available at:"; text += "<BR><a href=\"http://virtualhiker.sf.net/\">"; text += "http://virtualhiker.sf.net/</a></P>"; text += "</body></html>"; } return text; }
Code Sample 2:
private void triggerBuild(Properties props, String project, int rev) throws IOException { boolean doBld = Boolean.parseBoolean(props.getProperty(project + ".bld")); String url = props.getProperty(project + ".url"); if (!doBld || project == null || project.length() == 0) { System.out.println("BuildLauncher: Not configured to build '" + project + "'"); return; } else if (url == null) { throw new IOException("Tried to launch build for project '" + project + "' but " + project + ".url property is not defined!"); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); System.out.println(fmt.format(new Date()) + ": Triggering a build via: " + url); BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while (r.readLine() != null) ; System.out.println(fmt.format(new Date()) + ": Build triggered!"); LATEST_BUILD.put(project, rev); r.close(); System.out.println(fmt.format(new Date()) + ": triggerBuild() done!"); }
|
11
|
Code Sample 1:
public static void copyFile(String oldPath, String newPath) throws IOException { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } }
Code Sample 2:
public static void copyFile(String inName, String otName) throws Exception { File inFile = null; File otFile = null; try { inFile = new File(inName); otFile = new File(otName); } catch (Exception e) { e.printStackTrace(); } if (inFile == null || otFile == null) return; FileChannel sourceChannel = new FileInputStream(inFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(otFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
@Override @RemoteMethod public synchronized boolean copy(int idAnexo) { try { Anexo anexo = selectById(idAnexo); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Usuario usuario = (Usuario) auth.getPrincipal(); if (anexo.getAssinado() == 1 && anexo.getIdAssinadoPor() != usuario.getIdUsuario()) { deleteAnexoFromTemp(anexo); return false; } Carteira carteiraUsuario = carteiraService.selectById(usuario.getIdCarteira()); DocumentoDetalhes documentoDetalhes = anexo.getDocumentoDetalhes(); Set<Documento> documentos = documentoDetalhes.getDocumentosByCarteira(); boolean havePermission = false; for (Documento documento : documentos) { Carteira carteiraDocumento = documento.getCarteira(); if (carteiraDocumento != null) { if (carteiraDocumento.getIdCarteira() == carteiraUsuario.getIdCarteira()) { havePermission = true; System.out.println("tem permisssao: " + havePermission); break; } } } if (!havePermission) { System.out.println("Não tem permissao."); return false; } FileInputStream fis = new FileInputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); IOUtils.copy(fis, fos); String txtHistorico = "(Edição) -" + anexo.getAnexoNome() + "-"; txtHistorico += usuario.getUsuLogin(); Historico historico = new Historico(); historico.setCarteira(carteiraUsuario); historico.setDataHoraHistorico(new Date()); historico.setHistorico(txtHistorico); historico.setDocumentoDetalhes(documentoDetalhes); historico.setUsuario(usuario); historicoService.save(historico); return deleteAnexoFromTemp(anexo); } catch (FileNotFoundException e) { System.out.println("FileNotFoundException"); e.printStackTrace(); return false; } catch (IOException e) { System.out.println("IOException"); e.printStackTrace(); return false; } catch (Exception e) { System.out.println("AnexoServiceImpl.copy ERRO DESCONHECIDO"); e.printStackTrace(); return false; } }
Code Sample 2:
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)"); }
|
00
|
Code Sample 1:
protected void innerProcess(ProcessorURI curi) throws InterruptedException { Pattern regexpr = curi.get(this, STRIP_REG_EXPR); ReplayCharSequence cs = null; try { cs = curi.getRecorder().getReplayCharSequence(); } catch (Exception e) { curi.getNonFatalFailures().add(e); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr != null) { s = cs.toString(); } else { Matcher m = regexpr.matcher(cs); s = m.replaceAll(" "); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
Code Sample 2:
protected <T extends AbstractResponse> T readResponse(HttpUriRequest httpUriRequest, Class<T> clazz) throws IOException, TranslatorException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Executing request " + httpUriRequest.getURI()); } HttpResponse httpResponse = httpClient.execute(httpUriRequest); String response = EntityUtils.toString(httpResponse.getEntity()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Reading '" + response + "' into " + clazz.getName()); } T abstractResponse = TranslatorObjectMapper.instance().readValue(response, clazz); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Response object " + abstractResponse); } if (abstractResponse.getError() != null) { throw new TranslatorException(abstractResponse.getError()); } return abstractResponse; }
|
11
|
Code Sample 1:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
Code Sample 2:
public void copyFile(File s, File t) { try { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }
|
11
|
Code Sample 1:
public boolean update(int idPartida, partida partidaModificada) { int intResult = 0; String sql = "UPDATE partida " + "SET torneo_idTorneo = ?, " + " jugador_idJugadorNegras = ?, jugador_idJugadorBlancas = ?, " + " fecha = ?, " + " resultado = ?, " + " nombreBlancas = ?, nombreNegras = ?, eloBlancas = ?, eloNegras = ?, idApertura = ? " + " WHERE idPartida = " + idPartida; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement2(partidaModificada); 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:
protected void doBackupOrganizeType() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT organize_type_id,organize_type_name,width " + "FROM " + Common.ORGANIZE_TYPE_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_B_TABLE + " " + "(version_no,organize_type_id,organize_type_name,width) " + "VALUES (?,?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("organize_type_id")); ps.setString(3, result.getString("organize_type_name")); ps.setInt(4, result.getInt("width")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeType(): ERROR Inserting data " + "in T_SYS_ORGANIZE_B_TYPE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeType(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeType(): SQLException while committing or rollback"); } }
|
00
|
Code Sample 1:
protected File downloadFile(String href) { Map<String, File> currentDownloadDirMap = downloadedFiles.get(downloadDir); if (currentDownloadDirMap != null) { File downloadedFile = currentDownloadDirMap.get(href); if (downloadedFile != null) { return downloadedFile; } } else { downloadedFiles.put(downloadDir, new HashMap<String, File>()); currentDownloadDirMap = downloadedFiles.get(downloadDir); } URL url; File result; try { FilesystemUtils.forceMkdirIfNotExists(downloadDir); url = generateUrl(href); result = createUniqueFile(downloadDir, href); } catch (IOException e) { LOG.warn("Failed to create file for download", e); return null; } currentDownloadDirMap.put(href, result); LOG.info("Downloading " + url); try { IOUtils.copy(url.openStream(), new FileOutputStream(result)); } catch (IOException e) { LOG.warn("Failed to download file " + url); } return result; }
Code Sample 2:
private final void lookup() throws Exception { try { URL url; URLConnection urlConn; DataOutputStream printout; BufferedReader input; url = new URL("http://www.amazon.com/exec/obidos/search-handle-form"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "page=" + URLEncoder.encode("1") + "&index=" + URLEncoder.encode("music") + "&field-artist=" + URLEncoder.encode(artist) + "&field-title=" + URLEncoder.encode(title) + "&field-binding=" + URLEncoder.encode(""); printout.writeBytes(content); printout.flush(); printout.close(); input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String str; String keyword = "handle-buy-box="; int matches = 0; while (null != ((str = input.readLine()))) { int idStart = str.indexOf(keyword); if (idStart > 0) { idStart = idStart + keyword.length(); String id = str.substring(idStart, idStart + 10); status.append("Match: "); status.append(id); status.append(". "); if (verifyMatch(id, title)) { discID = id; imageURL = "http://images.amazon.com/images/P/" + id + ".01.LZZZZZZZ.jpg"; matchType = EXACT_MATCH; } } } input.close(); } catch (Exception e) { throw e; } }
|
11
|
Code Sample 1:
protected String getHashCode(String value) { if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin"); String retVal = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(value.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(this.toHexString(digest[i])); } retVal = sb.toString(); if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal); } catch (Exception e) { log.error("getHashCode(...) -> error occured generating hashcode ", e); } if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end"); return retVal; }
Code Sample 2:
private String getBytes(String in) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); byte[] passWordBytes = md5.digest(); String s = "["; for (int i = 0; i < passWordBytes.length; i++) s += passWordBytes[i] + ", "; s = s.substring(0, s.length() - 2); s += "]"; return s; }
|
11
|
Code Sample 1:
public static void zip() throws Exception { System.out.println("zip()"); ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(new File("/zip/myzip.zip"))); ZipEntry entry = new ZipEntry("asdf.script"); zipout.putNextEntry(entry); byte buffer[] = new byte[BLOCKSIZE]; FileInputStream in = new FileInputStream(new File("/zip/asdf.script")); for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length); in.close(); zipout.closeEntry(); zipout.close(); }
Code Sample 2:
protected File getFile(NameCategory category) throws IOException { File home = new File(System.getProperty("user.dir")); String fileName = String.format("%s.txt", category); File file = new File(home, fileName); if (file.exists()) { return file; } else { URL url = LocalNameGenerator.class.getResource("/" + fileName); if (url == null) { throw new IllegalStateException(String.format("Cannot find resource at %s", fileName)); } else { InputStream in = url.openStream(); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { IOUtils.copy(in, out); } finally { out.close(); } } finally { in.close(); } return file; } } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void unzipData(ZipFile zipfile, ZipEntry entry) { if (entry.getName().equals("backUpExternalInfo.out")) { File outputFile = new File("temp", entry.getName()); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } try { BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException e) { throw new BackupException(e.getMessage()); } } }
|
11
|
Code Sample 1:
private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); 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 void run() { XmlFilesFilter filter = new XmlFilesFilter(); String pathTemp = Settings.get("vo_store.databaseMetaCollection"); String sectionName = pathTemp.substring(1, pathTemp.indexOf("/", 2)); String templateName = VOAccess.getElementByName(settingsDB, "TEMPLATE", sectionName); String schemaName = VOAccess.getElementByName(settingsDB, "SCHEMA", sectionName); byte[] buf = new byte[1024]; Hashtable templateElements = null; try { URL xmlTemplateUrl = new URL(httpURI + settingsDB + "/" + templateName); URL getDocPathsAndValuesXslUrl = new URL(httpURI + settingsDB + "/" + "getDocPathsValuesAndDisplays.xsl"); org.w3c.dom.Document curTemplateXml = VOAccess.readDocument(xmlTemplateUrl); DOMResult templateResult = new DOMResult(); InputStream tempInput = getDocPathsAndValuesXslUrl.openStream(); javax.xml.transform.sax.SAXSource tempXslSource = new javax.xml.transform.sax.SAXSource(new org.xml.sax.InputSource(tempInput)); Transformer trans = TransformerFactory.newInstance().newTransformer(tempXslSource); trans.setParameter("schemaUrl", httpURI + settingsDB + "/" + schemaName); trans.transform(new javax.xml.transform.dom.DOMSource(curTemplateXml), templateResult); tempInput.close(); templateElements = VOAccess.displaysToHashtable(templateResult); ((CollectionManagementService) CollectionsManager.getService(xmldbURI + rootDB, false, "CollectionManager")).createCollection(rootDB + pathTemp); } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); } while (true) { File[] fileList = sourceMetaFilesDir.listFiles(filter); for (int i = 0; i < Math.min(fileList.length, 500); i++) { File newFile = fileList[i]; try { Document metaDoc = build.build(newFile); Element metaElm = metaDoc.getRootElement(); String dataFileName = metaElm.getChildText("Content"), previewFileName = metaElm.getChildText("Preview"); String objId = VOAccess.getUniqueId(); metaElm.getChild("Content").setText("videostore?type=doc&objId=" + objId); metaElm.getChild("Preview").setText("videostore?type=preview&objId=" + objId); boolean found = false; for (Iterator it = sourceDataFilesDirs.iterator(); it.hasNext() && !found; ) { String sourceDataFilesDir = (String) it.next(); File dataInput = new File(sourceDataFilesDir + "/" + dataFileName); if (dataInput.exists()) { found = true; BufferedInputStream inp = new BufferedInputStream(new FileInputStream(dataInput)); FileOutputStream outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".dat")); int read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); dataInput = new File(sourceDataFilesDir + "/" + previewFileName); inp = new BufferedInputStream(new FileInputStream(dataInput)); outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".jpg")); read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); curDirWriteTo++; if (curDirWriteTo >= targetDataFilesDirs.size()) { curDirWriteTo = 0; } } } if (!found) { newFile.renameTo(new File(newFile.getAbsolutePath() + ".not_found")); } else { String title = getValueByPath((String) templateElements.get("title"), metaDoc.getRootElement()); String description = getValueByPath((String) templateElements.get("description"), metaDoc.getRootElement()); String onlink = ""; if (null != templateElements.get("onlink")) { onlink = getValueByPath((String) templateElements.get("onlink"), metaDoc.getRootElement()); } String ncover = ""; if (null != templateElements.get("ncover")) { ncover = getValueByPath((String) templateElements.get("ncover"), metaDoc.getRootElement()); } String wcover = ""; if (null != templateElements.get("wcover")) { wcover = getValueByPath((String) templateElements.get("wcover"), metaDoc.getRootElement()); } String ecover = ""; if (null != templateElements.get("ecover")) { ecover = getValueByPath((String) templateElements.get("ecover"), metaDoc.getRootElement()); } String scover = ""; if (null != templateElements.get("scover")) { scover = getValueByPath((String) templateElements.get("scover"), metaDoc.getRootElement()); } String datefrom = ""; if (null != templateElements.get("datefrom")) { datefrom = getValueByPath((String) templateElements.get("datefrom"), metaDoc.getRootElement()); } String dateto = ""; if (null != templateElements.get("dateto")) { dateto = getValueByPath((String) templateElements.get("dateto"), metaDoc.getRootElement()); } String previewimg = ""; if (null != templateElements.get("previewimg")) { previewimg = getValueByPath((String) templateElements.get("previewimg"), metaDoc.getRootElement()); } String discRestr = "false"; String votingRestr = "false"; datefrom = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); dateto = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); Hashtable discussionFields = new Hashtable(); discussionFields.put("OBJECT_ID", objId); discussionFields.put("AUTHOR_ID", "auto"); discussionFields.put("AUTHOR_NAME", "auto"); discussionFields.put("OBJECT_SECTION", sectionName); discussionFields.put("OBJECT_PATH", pathTemp); discussionFields.put("FILE_PATH", ""); discussionFields.put("TITLE", title); discussionFields.put("DESCRIPTION", description); discussionFields.put("ONLINK", onlink); discussionFields.put("NCOVER", ncover); discussionFields.put("ECOVER", ecover); discussionFields.put("SCOVER", scover); discussionFields.put("WCOVER", wcover); discussionFields.put("PERIOD_START", datefrom); discussionFields.put("PERIOD_END", dateto); discussionFields.put("PREVIEW_IMG", previewimg); discussionFields.put("DISCUSSRESTRICTION", discRestr); discussionFields.put("VOTINGRESTRICTION", votingRestr); VOAccess.createDiscussionFile(discussionFields); VOAccess.updateLastItem(objId, sectionName); Collection col = CollectionsManager.getCollection(rootDB + pathTemp, true); XMLResource document = (XMLResource) col.createResource(objId + ".xml", XMLResource.RESOURCE_TYPE); document.setContent(outXml.outputString(metaElm)); col.storeResource(document); Indexer.index(objId); newFile.delete(); } } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); newFile.renameTo(new File(newFile.getAbsolutePath() + ".bad")); } } try { this.sleep(600000); } catch (InterruptedException ex1) { ex1.printStackTrace(); } } }
|
00
|
Code Sample 1:
public static void copy(File sourceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
private void download(String address, String localFileName, String host, int porta) { InputStream in = null; URLConnection conn = null; OutputStream out = null; System.out.println("Update.download() BAIXANDO " + address); try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); if (host != "" && host != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, porta)); conn = url.openConnection(proxy); } else { conn = url.openConnection(); } in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } }
|
11
|
Code Sample 1:
public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
Code Sample 2:
private static void _checkConfigFile() throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; boolean copy = false; File from = new java.io.File(filePath); if (!from.exists()) { Properties properties = new Properties(); properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY")); Company comp = PublicCompanyFactory.getDefaultCompany(); int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW"); for (int i = 1; i <= numberGenericVariables; i++) { properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY")); } try { properties.store(new java.io.FileOutputStream(filePath), null); } catch (Exception e) { Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e); } from = new java.io.File(filePath); copy = true; } String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File to = new java.io.File(tmpFilePath); if (!to.exists()) { to.createNewFile(); copy = true; } if (copy) { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e); } }
|
00
|
Code Sample 1:
public boolean delMail(MailObject mail) throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_MAIL_DEL + mail.getId()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isXmlContentType(response)) { HTTPUtil.consume(response.getEntity()); return true; } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
public static byte[] getURLContent(String urlPath) { HttpURLConnection conn = null; InputStream inStream = null; byte[] buffer = null; try { URL url = new URL(urlPath); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setUseCaches(false); conn.setDefaultUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(60000); conn.connect(); int repCode = conn.getResponseCode(); if (repCode == 200) { inStream = conn.getInputStream(); int contentLength = conn.getContentLength(); buffer = getResponseBody(inStream, contentLength); } } catch (Exception ex) { logger.error("", ex); } finally { try { if (inStream != null) { inStream.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception ex) { } } return buffer; }
|
00
|
Code Sample 1:
private static String digest(String buffer) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(buffer.getBytes()); return new String(encodeHex(md5.digest(key))); } catch (NoSuchAlgorithmException e) { } return null; }
Code Sample 2:
@Override public String resolveItem(String oldJpgFsPath) throws DatabaseException { if (oldJpgFsPath == null || "".equals(oldJpgFsPath)) throw new NullPointerException("oldJpgFsPath"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement statement = null; String ret = null; try { statement = getConnection().prepareStatement(SELECT_ITEM_STATEMENT); statement.setString(1, oldJpgFsPath); ResultSet rs = statement.executeQuery(); int i = 0; int id = -1; int rowsAffected = 0; while (rs.next()) { id = rs.getInt("id"); ret = rs.getString("imageFile"); i++; } if (id != -1 && new File(ret).exists()) { statement = getConnection().prepareStatement(UPDATE_ITEM_STATEMENT); statement.setInt(1, id); rowsAffected = statement.executeUpdate(); } else { return null; } if (rowsAffected == 1) { getConnection().commit(); LOGGER.debug("DB has been updated."); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback!"); } } catch (SQLException e) { LOGGER.error(e); } finally { closeConnection(); } return ret; }
|
00
|
Code Sample 1:
@Override public void vote(String urlString, Map<String, String> headData, Map<String, String> paramData) { HttpURLConnection httpConn = null; try { URL url = new URL(urlString); httpConn = (HttpURLConnection) url.openConnection(); String cookies = getCookies(httpConn); System.out.println(cookies); BufferedReader post = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GB2312")); String text = null; while ((text = post.readLine()) != null) { System.out.println(text); } } catch (MalformedURLException e) { e.printStackTrace(); throw new VoteBeanException("网址不正确", e); } catch (IOException e) { e.printStackTrace(); throw new VoteBeanException("不能打开网址", e); } }
Code Sample 2:
public static void replaceAll(File file, String substitute, String substituteReplacement) throws IOException { log.debug("Replace " + substitute + " by " + substituteReplacement); Pattern pattern = Pattern.compile(substitute); FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); Charset charset = Charset.forName("ISO-8859-15"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cb = decoder.decode(bb); Matcher matcher = pattern.matcher(cb); String outString = matcher.replaceAll(substituteReplacement); log.debug(outString); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); PrintStream ps = new PrintStream(fos); ps.print(outString); ps.close(); fos.close(); }
|
00
|
Code Sample 1:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
Code Sample 2:
public static Vector<Person> parseFriends(Worker me, SmEngine sme, Person resource) throws IOException { URL url = new URL(resource.getUrl()); long fid; if (sme.getProxy() == null) me.conn = (HttpURLConnection) url.openConnection(); else me.conn = (HttpURLConnection) url.openConnection(sme.getProxy()); me.conn.setReadTimeout(20 * 1000); Vector<Person> result; org.htmlparser.Parser parser; NodeList nl; NodeFilter[] filters1 = new NodeFilter[2]; filters1[0] = new TagNameFilter("a"); filters1[1] = new HasAttributeFilter("class", "signup_btn uiButton uiButtonSpecial uiButtonLarge"); NodeFilter[] filters2 = new NodeFilter[3]; filters2[0] = new TagNameFilter("a"); filters2[1] = new HasAttributeFilter("class", "title"); filters2[2] = new HasParentFilter(new HasAttributeFilter("class", "UIPortrait_Text")); try { parser = new org.htmlparser.Parser(me.conn); } catch (ParserException e) { System.err.println(e.getMessage()); return null; } try { nl = parser.parse(new AndFilter(filters1)); fid = Long.parseLong(((LinkTag) nl.elementAt(0)).getLink().split("(fid=|&)")[2]); } catch (ParserException e) { e.printStackTrace(); return null; } result = new Vector<Person>(); try { nl = parser.parse(new AndFilter(filters2)); } catch (ParserException e) { e.printStackTrace(); return null; } Person p; for (int i = 0; i < nl.size(); i++) { p = sme.getPerson(fid, ((TagNode) nl.elementAt(i)).getAttribute("title"), ((TagNode) nl.elementAt(i)).getAttribute("href")); resource.addFriend(p); p.addFriend(resource); synchronized (p) { if (!p.isInQueue()) { p.setInQueue(true); sme.addResource(p); } } } return result; }
|
00
|
Code Sample 1:
public static final synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally."); nsae.printStackTrace(); } } digest.update(data.getBytes()); return encodeHex(digest.digest()); }
Code Sample 2:
public void initURL(URL url, boolean cache) throws IOException { this.url = url; if (cache) { System.out.println(getClass().getName() + ": caching '" + url + "'"); InputStream urlIS = new BufferedInputStream(url.openStream(), 1024 * 30); file = File.createTempFile("_dss_", "_dss_"); file.deleteOnExit(); OutputStream cachedOS = new BufferedOutputStream(new FileOutputStream(file), 1024 * 30); byte[] buf = new byte[1024 * 4]; long cachedBytesCount = 0; int count = 0; while ((count = urlIS.read(buf)) > 0) { cachedOS.write(buf, 0, count); cachedBytesCount += count; } urlIS.close(); cachedOS.flush(); cachedOS.close(); this.cached = true; System.out.println(getClass().getName() + ": cached " + cachedBytesCount + " bytes into '" + file.getAbsolutePath() + "'"); } }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
11
|
Code Sample 1:
static final void executeUpdate(Collection<String> queries, DBConnector connector) throws IOException { Connection con = null; Statement st = null; try { con = connector.getDB(); con.setAutoCommit(false); st = con.createStatement(); for (String s : queries) st.executeUpdate(s); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new IOException(e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } }
Code Sample 2:
public Project createProject(int testbedID, String name, String description) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO Projects(testbedID, name, " + "description) VALUES (" + testbedID + ", '" + name + "', '" + description + "')"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM Projects WHERE " + " testbedID = " + testbedID + " AND " + " name = '" + name + "' AND " + " description = '" + description + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; }
|
00
|
Code Sample 1:
@Test public void testDoGet() throws Exception { HttpHost targetHost = new HttpHost("localhost", 8080, "http"); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("vince", "test56")); try { HttpGet httpget = new HttpGet("http://localhost:8080/objectwiz/api?invokeFacetOperation=createNewEntity&objectClassName=org.objectwiz.testapp.jee5.addressbook.Person&applicationName=addressbook&methodReference=persist(E)&args=(lastname=toto)"); System.out.println("executing request " + httpget.getURI()); HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header h = headers[i]; System.out.println(h.getName() + "/" + h.getValue()); } assertEquals(response.getStatusLine().getStatusCode(), 200); System.out.println("----------------------------------------"); if (entity != null) { System.out.println("response content length" + entity.getContentLength()); System.out.println(entity.getContentType().getName() + "/" + entity.getContentType().getValue()); } httpget.abort(); } finally { client.getConnectionManager().shutdown(); } }
Code Sample 2:
private void work(String[] args) throws Exception { String dictLocation = CONTENT_URL; String cpeContentDirName = CONTENT_DIR; String fn = dictLocation.substring(dictLocation.lastIndexOf("/") + 1); File destFile = new File(cpeContentDirName + File.separator + fn); URL url = new URL(dictLocation); URLConnection conn = url.openConnection(); conn.connect(); long lmodifiedRemote = conn.getLastModified(); boolean needToDownload = false; if (destFile.exists()) { System.out.println(destFile.getAbsolutePath() + " exists, check modification time"); long lmodifiedLocal = destFile.lastModified(); if (lmodifiedRemote > lmodifiedLocal) { System.out.println("Server file is newer, need to download"); needToDownload = true; } else { System.out.println("Local version is newer, no need to download"); } } else { System.out.println("Local version doesn't exist, need to download"); needToDownload = true; } if (needToDownload) { InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(destFile); byte[] buff = new byte[8192]; int read = 0; while ((read = is.read(buff)) > 0) { fos.write(buff, 0, read); } fos.flush(); fos.close(); is.close(); } }
|
11
|
Code Sample 1:
public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
Code Sample 2:
public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
|
00
|
Code Sample 1:
private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
public static JsonNode getJSONFromURL(String httpUrl) throws Exception { URL url; InputStream inputStream = null; DataInputStream dataInputStream; try { url = new URL(httpUrl); inputStream = url.openStream(); dataInputStream = new DataInputStream(new BufferedInputStream(inputStream)); return JsonUtil.getNode(dataInputStream); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ioe) { } } }
Code Sample 2:
@RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) { InputStream input = null; ServletOutputStream output = null; try { String savePath = request.getSession().getServletContext().getRealPath("/upload"); String fileType = ".log"; String dbFileName = "83tomcat日志测试哦"; String downloadFileName = dbFileName + fileType; String finalPath = "\\2011-12\\01\\8364b45f-244d-41b6-bbf48df32064a935"; downloadFileName = new String(downloadFileName.getBytes("GBK"), "ISO-8859-1"); File downloadFile = new File(savePath + finalPath); if (!downloadFile.getParentFile().exists()) { downloadFile.getParentFile().mkdirs(); } if (!downloadFile.isFile()) { FileUtils.touch(downloadFile); } response.setContentType("aapplication/vnd.ms-excel ;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("content-disposition", "attachment; filename=" + downloadFileName); input = new FileInputStream(downloadFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { logger.error("Exception: ", e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
|
11
|
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:
public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
|
00
|
Code Sample 1:
public static void main(String[] args) { final MavenDeployerGui gui = new MavenDeployerGui(); final Chooser repositoryChooser = new Chooser(gui.formPanel, JFileChooser.DIRECTORIES_ONLY); final Chooser artifactChooser = new Chooser(gui.formPanel, JFileChooser.FILES_ONLY); final Chooser pomChooser = new Chooser(gui.formPanel, JFileChooser.FILES_ONLY, new POMFilter()); gui.cancel.setEnabled(false); gui.cbDeployPOM.setVisible(false); gui.cbDeployPOM.setEnabled(false); gui.mavenBin.setText(findMavenExecutable()); gui.repositoryBrowser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File repo = repositoryChooser.chooseFrom(currentDir); if (repo != null) { currentDir = repositoryChooser.currentFolder; gui.repositoryURL.setText(repo.getAbsolutePath()); } } }); gui.artifactBrowser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File artifact = artifactChooser.chooseFrom(currentDir); if (artifact != null) { currentDir = artifactChooser.currentFolder; gui.artifactFile.setText(artifact.getAbsolutePath()); } } }); gui.deploy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { deployer = new Deployer(gui, pom); deployer.execute(); } }); gui.clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { gui.console.setText(""); } }); gui.cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (deployer != null) { deployer.stop(); deployer = null; } } }); gui.cbDeployPOM.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { readPOM(gui); } }); gui.loadPOM.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pom = pomChooser.chooseFrom(currentDir); if (pom != null) { currentDir = pomChooser.currentFolder; readPOM(gui); gui.cbDeployPOM.setText("Deploy also " + pom.getAbsolutePath()); gui.cbDeployPOM.setEnabled(true); gui.cbDeployPOM.setVisible(true); } } }); String version = ""; try { URL url = Thread.currentThread().getContextClassLoader().getResource("META-INF/maven/com.mycila.maven/maven-deployer/pom.properties"); Properties p = new Properties(); p.load(url.openStream()); version = " " + p.getProperty("version"); } catch (Exception ignored) { version = " x.y"; } JFrame frame = new JFrame("Maven Deployer" + version + " - By Mathieu Carbou (http://blog.mycila.com)"); frame.setContentPane(gui.formPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); }
Code Sample 2:
protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
|
00
|
Code Sample 1:
private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } }
Code Sample 2:
public static String readFromUrl(String url) { URL url_ = null; URLConnection uc = null; BufferedReader in = null; StringBuilder str = new StringBuilder(); try { url_ = new URL(url); uc = url_.openConnection(); in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) str.append(inputLine); in.close(); } catch (IOException e) { e.printStackTrace(); } return str.toString(); }
|
11
|
Code Sample 1:
private static synchronized byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance(algoritmo); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
@Override public String getMD5(String host) { String res = ""; Double randNumber = Math.random() + System.currentTimeMillis(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(randNumber.toString().getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; }
|
00
|
Code Sample 1:
@Override public String post(final FetchInfos fetchInfos, final String data) throws HttpException { URL url = null; try { url = new URL(fetchInfos.getUri()); } catch (MalformedURLException exception) { throw new HttpException("uri is malformed '" + fetchInfos.getUri() + "'", exception); } HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } InputStream input = null; try { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); final DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); input = connection.getInputStream(); if ("gzip".equals(connection.getHeaderField("content-encoding"))) { input = new GZIPInputStream(input); } if (HttpServiceImpl.LOGGER.isDebugEnabled()) { this.logConnection(connection); input = new LoggingInputStream(input); } } catch (SocketTimeoutException exception) { fetchInfos.setResult(FETCHING_RESULT.TIME_OUT); throw new HttpException("get '" + fetchInfos.getUri() + "' timeout", exception); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } fetchInfos.setResult(FETCHING_RESULT.OK); String response = null; try { response = this.toString(input); } catch (IOException exception) { throw new HttpException("converting inputstream to string failed", exception); } return response; }
Code Sample 2:
public void process(String t) { try { MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST); md5.reset(); md5.update(t.getBytes()); callback.display(null, digestToHexString(md5.digest())); } catch (Exception ex) { callback.display(null, "[failed]"); } }
|
00
|
Code Sample 1:
public static void copyFile(File from, File to) throws IOException { ensureFile(to); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CURRENCY")); pst.setInt(1, curr.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
|
11
|
Code Sample 1:
public static void compressAll(File dir, File file) throws IOException { if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.setLevel(0); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytesRead; for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); }
Code Sample 2:
public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
@Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtil.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, null, compareResponse.getControls()); }
Code Sample 2:
protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); }
|
00
|
Code Sample 1:
private String readAboutText(String urlStr) { String text = null; try { URL url = this.getClass().getResource(urlStr); InputStreamReader reader = new InputStreamReader(url.openStream()); StringWriter writer = new StringWriter(); int character = reader.read(); while (character != -1) { writer.write(character); character = reader.read(); } text = writer.toString(); } catch (IOException e) { e.printStackTrace(); text = "<html><body><b>Author:</b><br>" + aAuthor + "<br>"; text += "<a href=\"mailto:jhuwaldt@mac.com\">jhuwaldt@mac.com</a><br>"; text += "<P ALIGN=CENTER><BR>" + aName + " comes with ABSOLUTELY NO WARRANTY;"; text += "<BR>This is free software, and you are welcome to redistribute "; text += "it and it's source code under certain conditions."; text += "<BR>Source code is available at:"; text += "<BR><a href=\"http://virtualhiker.sf.net/\">"; text += "http://virtualhiker.sf.net/</a></P>"; text += "</body></html>"; } return text; }
Code Sample 2:
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (Exception e) { e.printStackTrace(); } return convertToHex(md5hash); }
|
11
|
Code Sample 1:
public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); }
Code Sample 2:
public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
|
00
|
Code Sample 1:
private void connect(URL url) throws IOException { String protocol = url.getProtocol(); if (!protocol.equals("http")) throw new IllegalArgumentException("URL must use 'http:' protocol"); int port = url.getPort(); if (port == -1) port = 80; fileName = url.getFile(); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); toServer = new OutputStreamWriter(conn.getOutputStream()); fromServer = conn.getInputStream(); }
Code Sample 2:
public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); }
|
11
|
Code Sample 1:
private String convert(InputStream input, String encoding) throws Exception { Process p = Runtime.getRuntime().exec("tidy -q -f /dev/null -wrap 0 --output-xml yes --doctype omit --force-output true --new-empty-tags " + emptyTags + " --quote-nbsp no -utf8"); Thread t = new CopyThread(input, p.getOutputStream()); t.start(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(p.getInputStream(), output); p.waitFor(); t.join(); return output.toString(); }
Code Sample 2:
public static void importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + 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()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static GoogleResponse getElevation(String lat, String lon) throws IOException { String url = "http://maps.google.com/maps/api/elevation/xml?locations="; url = url + String.valueOf(lat); url = url + ","; url = url + String.valueOf(lon); url = url + "&sensor=false"; BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line; GoogleResponse googleResponse = new GoogleResponse(); googleResponse.lat = Double.valueOf(lat); googleResponse.lon = Double.valueOf(lon); while ((line = in.readLine()) != null) { line = line.trim(); if (line.startsWith("<status>")) { line = line.replace("<status>", ""); line = line.replace("</status>", ""); googleResponse.status = line; if (!line.toLowerCase().equals("ok")) return googleResponse; } else if (line.startsWith("<elevation>")) { line = line.replace("<elevation>", ""); line = line.replace("</elevation>", ""); googleResponse.elevation = Double.valueOf(line); return googleResponse; } } return googleResponse; }
Code Sample 2:
private static String extractFirstLine(String urlToFile) { try { URL url = new URL(urlToFile); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); return br.readLine(); } catch (Exception e) { return null; } }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private void stripOneFilex(File inFile, File outFile) throws IOException { StreamTokenizer reader = new StreamTokenizer(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); reader.slashSlashComments(false); reader.slashStarComments(false); reader.eolIsSignificant(true); int token; while ((token = reader.nextToken()) != StreamTokenizer.TT_EOF) { switch(token) { case StreamTokenizer.TT_NUMBER: throw new IllegalStateException("didn't expect TT_NUMBER: " + reader.nval); case StreamTokenizer.TT_WORD: System.out.print(reader.sval); writer.write("WORD:" + reader.sval, 0, reader.sval.length()); default: char outChar = (char) reader.ttype; System.out.print(outChar); writer.write(outChar); } } }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") public static void createInstance(ExternProtoDeclare externProtoDeclare) { ExternProtoDeclareImport epdi = new ExternProtoDeclareImport(); HashMap<String, ProtoDeclareImport> protoMap = X3DImport.getTheImport().getCurrentParser().getProtoMap(); boolean loadedFromWeb = false; File f = null; URL url = null; List<String> urls = externProtoDeclare.getUrl(); String tmpUrls = urls.toString(); urls = Util.splitStringToListOfStrings(tmpUrls); String protoName = null; int urlCount = urls.size(); for (int urlIndex = 0; urlIndex < urlCount; urlIndex++) { try { String path = urls.get(urlIndex); if (path.startsWith("\"") && path.endsWith("\"")) path = path.substring(1, path.length() - 1); int hashMarkPos = path.indexOf("#"); int urlLength = path.length(); if (hashMarkPos == -1) path = path.substring(0, urlLength); else { protoName = path.substring(hashMarkPos + 1, urlLength); path = path.substring(0, hashMarkPos); } if (path.toLowerCase().startsWith("http://")) { String filename = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); String fileext = path.substring(path.lastIndexOf("."), path.length()); f = File.createTempFile(filename, fileext); url = new URL(path); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); url = f.toURI().toURL(); loadedFromWeb = true; } else { if (path.startsWith("/") || (path.charAt(1) == ':')) { } else { File x3dfile = X3DImport.getTheImport().getCurrentParser().getFile(); path = Util.getRealPath(x3dfile) + path; } f = new File(path); url = f.toURI().toURL(); Object testContent = url.getContent(); if (testContent == null) continue; loadedFromWeb = false; } X3DDocument x3dDocument = null; try { x3dDocument = X3DDocument.Factory.parse(f); } catch (XmlException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } Scene scene = x3dDocument.getX3D().getScene(); ProtoDeclare[] protos = scene.getProtoDeclareArray(); ProtoDeclare protoDeclare = null; if (protoName == null) { protoDeclare = protos[0]; } else { for (ProtoDeclare proto : protos) { if (proto.getName().equals(protoName)) { protoDeclare = proto; break; } } } if (protoDeclare == null) continue; ProtoBody protoBody = protoDeclare.getProtoBody(); epdi.protoBody = protoBody; protoMap.put(externProtoDeclare.getName(), epdi); break; } catch (MalformedURLException e) { } catch (IOException e) { } finally { if (loadedFromWeb && f != null) { f.delete(); } } } }
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; }
|
00
|
Code Sample 1:
public static String getHash(String key) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); return new BigInteger(digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return key; } }
Code Sample 2:
@Override public void incluir(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "insert into cliente select nextval('sq_cliente') as cod_cliente, ? as nome, ? as sexo, ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, cliente.getNome()); stmt.setString(2, cliente.getSexo()); stmt.setInt(3, cliente.getCidade().getCodCidade()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de inserir dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
|
00
|
Code Sample 1:
public void load() { try { isSourceWorking = true; URLConnection urlConnection = url.openConnection(); ontologyServiceMetaData.setName("Ontology for " + url.getFile()); parseDocument(urlConnection.getInputStream()); buildTree(); isSourceWorking = true; String statusOKMessage = PedroResources.getMessage("ontology.statusOK", url.getFile()); status = new StringBuffer(); status.append(statusOKMessage); } catch (Exception err) { err.printStackTrace(System.out); String statusErrorMessage = PedroResources.getMessage("ontology.statusError", err.toString()); status.append(statusErrorMessage); isSourceWorking = false; } }
Code Sample 2:
private void insert(Connection c) throws SQLException { if (m_fromDb) throw new IllegalStateException("The record already exists in the database"); StringBuffer names = new StringBuffer("INSERT INTO ifServices (nodeID,ipAddr,serviceID"); StringBuffer values = new StringBuffer("?,?,?"); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) { values.append(",?"); names.append(",ifIndex"); } if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) { values.append(",?"); names.append(",status"); } if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { values.append(",?"); names.append(",lastGood"); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { values.append(",?"); names.append(",lastFail"); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) { values.append(",?"); names.append(",source"); } if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) { values.append(",?"); names.append(",notify"); } if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) { values.append(",?"); names.append(",qualifier"); } names.append(") VALUES (").append(values).append(')'); if (log().isDebugEnabled()) log().debug("DbIfServiceEntry.insert: SQL insert statment = " + names.toString()); PreparedStatement stmt = null; PreparedStatement delStmt = null; final DBUtils d = new DBUtils(getClass()); try { stmt = c.prepareStatement(names.toString()); d.watch(stmt); names = null; int ndx = 1; stmt.setInt(ndx++, m_nodeId); stmt.setString(ndx++, m_ipAddr.getHostAddress()); stmt.setInt(ndx++, m_serviceId); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) stmt.setInt(ndx++, m_ifIndex); if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) stmt.setString(ndx++, new String(new char[] { m_status })); if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { stmt.setTimestamp(ndx++, m_lastGood); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { stmt.setTimestamp(ndx++, m_lastFail); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) stmt.setString(ndx++, new String(new char[] { m_source })); if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) stmt.setString(ndx++, new String(new char[] { m_notify })); if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) stmt.setString(ndx++, m_qualifier); int rc; try { rc = stmt.executeUpdate(); } catch (SQLException e) { log().warn("ifServices DB insert got exception; will retry after " + "deletion of any existing records for this ifService " + "that are marked for deletion.", e); c.rollback(); String delCmd = "DELETE FROM ifServices WHERE status = 'D' " + "AND nodeid = ? AND ipAddr = ? AND serviceID = ?"; delStmt = c.prepareStatement(delCmd); d.watch(delStmt); delStmt.setInt(1, m_nodeId); delStmt.setString(2, m_ipAddr.getHostAddress()); delStmt.setInt(3, m_serviceId); rc = delStmt.executeUpdate(); rc = stmt.executeUpdate(); } log().debug("insert(): SQL update result = " + rc); } finally { d.cleanUp(); } m_fromDb = true; m_changed = 0; }
|
00
|
Code Sample 1:
private Image getIcon(Element e) { if (!addIconsToButtons) { return null; } else { NodeList nl = e.getElementsByTagName("rc:iconURL"); if (nl.getLength() > 0) { String urlString = nl.item(0).getTextContent(); try { Image img = new Image(Display.getCurrent(), new URL(urlString).openStream()); return img; } catch (Exception exception) { logger.warn("Can't read " + urlString + " using default icon instead."); } } return new Image(Display.getCurrent(), this.getClass().getResourceAsStream("/res/default.png")); } }
Code Sample 2:
protected void invoke(String path, Object request, Callback<Object> callback) throws IOException, ClassNotFoundException { Assert.notNull(callback, "callback cant be null"); URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setDefaultUseCaches(false); connection.setRequestMethod("POST"); connection.connect(); try { ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream()); try { output.writeObject(request); output.flush(); } finally { output.close(); } ObjectInputStream input = new ObjectInputStream(connection.getInputStream()); try { for (; ; ) { Object result = input.readObject(); if (result == null) { break; } callback.onSuccess(result); } } finally { input.close(); } } finally { connection.disconnect(); } }
|
11
|
Code Sample 1:
public static String sendRequest(String urlstring) { URL url; String line; Log.i("DVBMonitor", "Please wait while receiving data from dvb..."); try { url = new URL(urlstring); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); if ((line = in.readLine()) != null) { return line; } else { return null; } } catch (Exception ex) { Log.e("DVBMonitor", ex.toString() + " while sending request to dvb"); return null; } }
Code Sample 2:
public static void loadPages() throws IOException { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Collection<Class<? extends BasePage>> pages = new ArrayList<Class<? extends BasePage>>(); Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName()); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int comment = line.indexOf('#'); if (comment >= 0) line = line.substring(0, comment); String name = line.trim(); if (name.length() == 0) continue; Class<?> clz = Class.forName(name, true, ldr); if (BasePage.class.isAssignableFrom(clz)) { pages.add(clz.asSubclass(BasePage.class)); } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { is.close(); } catch (Exception ex) { } } } pageTypes = pages; }
|
11
|
Code Sample 1:
public static boolean update(Orgao orgao) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update orgao set nome = (?) where id_orgao= ?"; pst = c.prepareStatement(sql); pst.setString(1, orgao.getNome()); pst.setInt(2, orgao.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[OrgaoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
public ProgramProfilingSymbol deleteProfilingSymbol(int id) throws AdaptationException { ProgramProfilingSymbol profilingSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramProfilingSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program profiling " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingSymbol = getProfilingSymbol(resultSet); query = "DELETE FROM ProgramProfilingSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProfilingSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return profilingSymbol; }
|
00
|
Code Sample 1:
public static Set<String> getServices(String url) { Set<String> services = new HashSet<String>(); try { URL ws_url = new URL(url); URLConnection urlConn; DataInputStream dis; try { urlConn = ws_url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); dis = new DataInputStream(urlConn.getInputStream()); String s; int fpos = 0; int lpos; int lslash; String sn; while ((s = dis.readLine()) != null) { if (s.contains("?wsdl")) { fpos = s.indexOf("\"") + 1; lpos = s.indexOf("?"); s = s.substring(fpos, lpos); if (s.startsWith("http")) s = s.substring(7); lslash = s.lastIndexOf('/'); sn = s.substring(lslash + 1); if (!sn.equals("Version") && !sn.equals("AdminService")) services.add(url + "/" + sn); } } dis.close(); } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e1) { e1.printStackTrace(); } return services; }
Code Sample 2:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
|
00
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String pluginPathInfo = pathInfo.substring(prefix.length()); String gwtPathInfo = pluginPathInfo.substring(pluginKey.length() + 1); String clPath = CLASSPATH_PREFIX + gwtPathInfo; InputStream input = cl.getResourceAsStream(clPath); if (input != null) { try { OutputStream output = resp.getOutputStream(); IOUtils.copy(input, output); } finally { input.close(); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Code Sample 2:
public static String callApi(String api, String paramname, String paramvalue) { String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/" + api, paramname, paramvalue); u = SSOUtil.addParameter(u, "servicekey", SSOFilter.getServicekey()); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } }
|
00
|
Code Sample 1:
public void configureKerberos(boolean overwriteExistingSetup) throws Exception { OutputStream keyTabOut = null; InputStream keyTabIn = null; OutputStream krb5ConfOut = null; try { keyTabIn = loadKeyTabResource(keyTabResource); File file = new File(keyTabRepository + keyTabResource); if (!file.exists() || overwriteExistingSetup) { keyTabOut = new FileOutputStream(file, false); if (logger.isDebugEnabled()) logger.debug("Installing keytab file to : " + file.getAbsolutePath()); IOUtils.copy(keyTabIn, keyTabOut); } File krb5ConfFile = new File(System.getProperty("java.security.krb5.conf", defaultKrb5Config)); if (logger.isDebugEnabled()) logger.debug("Using Kerberos config file : " + krb5ConfFile.getAbsolutePath()); if (!krb5ConfFile.exists()) throw new Exception("Kerberos config file not found : " + krb5ConfFile.getAbsolutePath()); FileInputStream fis = new FileInputStream(krb5ConfFile); Wini krb5Conf = new Wini(KerberosConfigUtil.toIni(fis)); Ini.Section krb5Realms = krb5Conf.get("realms"); String windowsDomainSetup = krb5Realms.get(kerberosRealm); if (kerberosRealm == null || overwriteExistingSetup) { windowsDomainSetup = "{ kdc = " + keyDistributionCenter + ":88 admin_server = " + keyDistributionCenter + ":749 default_domain = " + kerberosRealm.toLowerCase() + " }"; krb5Realms.put(kerberosRealm, windowsDomainSetup); } Ini.Section krb5DomainRealms = krb5Conf.get("domain_realm"); String domainRealmSetup = krb5DomainRealms.get(kerberosRealm.toLowerCase()); if (domainRealmSetup == null || overwriteExistingSetup) { krb5DomainRealms.put(kerberosRealm.toLowerCase(), kerberosRealm); krb5DomainRealms.put("." + kerberosRealm.toLowerCase(), kerberosRealm); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); krb5Conf.store(baos); InputStream bios = new ByteArrayInputStream(baos.toByteArray()); bios = KerberosConfigUtil.toKrb5(bios); krb5ConfOut = new FileOutputStream(krb5ConfFile, false); IOUtils.copy(bios, krb5ConfOut); } catch (Exception e) { logger.error("Error while configuring Kerberos :" + e.getMessage(), e); throw e; } finally { IOUtils.closeQuietly(keyTabOut); IOUtils.closeQuietly(keyTabIn); IOUtils.closeQuietly(krb5ConfOut); } }
Code Sample 2:
public static String md5hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("MD5"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
|
00
|
Code Sample 1:
protected void processAnnotationsJndi(URL url) { try { URLConnection urlConn = url.openConnection(); DirContextURLConnection dcUrlConn; if (!(urlConn instanceof DirContextURLConnection)) { sm.getString("contextConfig.jndiUrlNotDirContextConn", url); return; } dcUrlConn = (DirContextURLConnection) urlConn; dcUrlConn.setUseCaches(false); String type = dcUrlConn.getHeaderField(ResourceAttributes.TYPE); if (ResourceAttributes.COLLECTION_TYPE.equals(type)) { Enumeration<String> dirs = dcUrlConn.list(); while (dirs.hasMoreElements()) { String dir = dirs.nextElement(); URL dirUrl = new URL(url.toString() + '/' + dir); processAnnotationsJndi(dirUrl); } } else { if (url.getPath().endsWith(".class")) { InputStream is = null; try { is = dcUrlConn.getInputStream(); processAnnotationsStream(is); } catch (IOException e) { logger.error(sm.getString("contextConfig.inputStreamJndi", url), e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } catch (IOException e) { logger.error(sm.getString("contextConfig.jndiUrl", url), e); } }
Code Sample 2:
@Test public final void testImportODScontentXml() throws Exception { URL url = ODSTableImporterTest.class.getResource("/Messages.ods_FILES/content.xml"); String systemId = url.getPath(); InputStream in = url.openStream(); ODSTableImporter b = new ODSTableImporter(); b.importODSContentXml(systemId, in, null); assertMessagesOds(b); }
|
11
|
Code Sample 1:
@Override public User login(String username, String password) { User user = null; try { user = (User) em.createQuery("Select o from User o where o.username = :username").setParameter("username", username).getSingleResult(); } catch (NoResultException e) { throw new NestedException(e.getMessage(), e); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(password.getBytes("UTF-8")); byte[] hash = digest.digest(); BigInteger bigInt = new BigInteger(1, hash); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } if (hashtext.equals(user.getPassword())) return user; } catch (Exception e) { throw new NestedException(e.getMessage(), e); } return null; }
Code Sample 2:
public static String plainToMD(LoggerCollection loggerCol, String input) { byte[] byteHash = null; MessageDigest md = null; StringBuilder md4result = new StringBuilder(); try { md = MessageDigest.getInstance("MD4", new BouncyCastleProvider()); md.reset(); md.update(input.getBytes("UnicodeLittleUnmarked")); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { md4result.append(Integer.toHexString(0xFF & byteHash[i])); } } catch (UnsupportedEncodingException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } catch (NoSuchAlgorithmException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } return (md4result.toString()); }
|
11
|
Code Sample 1:
public static void main(String args[]) { InputStream input = System.in; OutputStream output = System.out; if (args.length > 0) { try { input = new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[0]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[0]); System.exit(-1); } } if (args.length > 1) { try { output = new FileOutputStream(args[1]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[1]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[1]); System.exit(-1); } } byte buffer[] = new byte[512]; int len; try { while ((len = input.read(buffer)) > 0) output.write(buffer, 0, len); } catch (IOException e) { System.err.println("Error copying file"); } finally { input.close(); output.close(); } }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public static void copy(final File source, final File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); dest.setLastModified(source.lastModified()); } finally { close(in); close(out); } }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
00
|
Code Sample 1:
public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } }
Code Sample 2:
protected static String getInitialUUID() { if (myRand == null) { myRand = new Random(); } long rand = myRand.nextLong(); String sid; try { sid = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { sid = Thread.currentThread().getName(); } StringBuffer sb = new StringBuffer(); sb.append(sid); sb.append(":"); sb.append(Long.toString(rand)); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); StringBuffer sb2 = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; sb2.append(Integer.toHexString(b)); } int begin = myRand.nextInt(); if (begin < 0) begin = begin * -1; begin = begin % 8; return sb2.toString().substring(begin, begin + 18).toUpperCase(); }
|
11
|
Code Sample 1:
public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph tgt = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { tgt = manager.getTargetGraph(); if (tgt != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.ORANGES); factory.visit(tgt); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No target graph loaded."); } } catch (Exception e) { return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
Code Sample 2:
public static void copyFile(File srcFile, File dstFile) { logger.info("Create file : " + dstFile.getPath()); try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel dstChannel = new FileOutputStream(dstFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public String downloadToSdCard(String localFileName, String suffixFromHeader, String extension) { InputStream in = null; FileOutputStream fos = null; String absolutePath = null; try { Log.i(TAG, "Opening URL: " + url); StreamAndHeader inAndHeader = HTTPUtils.openWithHeader(url, suffixFromHeader); if (inAndHeader == null || inAndHeader.mStream == null) { return null; } in = inAndHeader.mStream; String sdcardpath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); String headerValue = suffixFromHeader == null || inAndHeader.mHeaderValue == null ? "" : inAndHeader.mHeaderValue; headerValue = headerValue.replaceAll("[-:]*\\s*", ""); String filename = sdcardpath + "/" + localFileName + headerValue + (extension == null ? "" : extension); mSize = in.available(); Log.i(TAG, "Downloading " + filename + ", size: " + mSize); fos = new FileOutputStream(new File(filename)); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int readsize = buffersize; mCount = 0; while (readsize != -1) { readsize = in.read(buffer, 0, buffersize); if (readsize > 0) { Log.i(TAG, "Read " + readsize + " bytes..."); fos.write(buffer, 0, readsize); mCount += readsize; } } fos.flush(); fos.close(); FileInputStream controlIn = new FileInputStream(filename); mSavedSize = controlIn.available(); Log.v(TAG, "saved size: " + mSavedSize); mAbsolutePath = filename; done(); } catch (Exception e) { Log.e(TAG, "LoadingWorker.run", e); } finally { HTTPUtils.close(in); } return mAbsolutePath; }
Code Sample 2:
private Tuple execute(final HttpMethodBase method, int numTries) throws IOException { final Timer timer = Metric.newTimer("RestClientImpl.execute"); try { final int sc = httpClient.executeMethod(method); if (sc < OK_MIN || sc > OK_MAX) { throw new RestException("Unexpected status code: " + sc + ": " + method.getStatusText() + " -- " + method, sc); } final InputStream in = method.getResponseBodyAsStream(); try { final StringWriter writer = new StringWriter(2048); IOUtils.copy(in, writer, method.getResponseCharSet()); return new Tuple(sc, writer.toString()); } finally { in.close(); } } catch (NullPointerException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (SocketException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (IOException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw e; } finally { method.releaseConnection(); timer.stop(); } }
|
11
|
Code Sample 1:
private void copyFile(File source) throws IOException { File backup = new File(source.getCanonicalPath() + ".backup"); if (!backup.exists()) { FileChannel srcChannel = new FileInputStream(source).getChannel(); backup.createNewFile(); FileChannel dstChannel = new FileOutputStream(backup).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
Code Sample 2:
@Override public void run() { try { File dest = new File(location); if ((dest.getParent() != null && !dest.getParentFile().isDirectory() && !dest.getParentFile().mkdirs())) { throw new IOException("Impossible de créer un dossier (" + dest.getParent() + ")."); } else if (dest.exists() && !dest.delete()) { throw new IOException("Impossible de supprimer un ancien fichier (" + dest + ")."); } else if (!dest.createNewFile()) { throw new IOException("Impossible de créer un fichier (" + dest + ")."); } FileChannel in = new FileInputStream(file).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); } finally { in.close(); out.close(); } } catch (Exception e) { Main.fenetre().erreur(Fenetre.ERREUR_FATALE_UPDATE, e); } finally { file.delete(); } }
|
11
|
Code Sample 1:
private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
Code Sample 2:
protected byte[] readGZippedBytes(TupleInput in) { final boolean is_compressed = in.readBoolean(); byte array[] = readBytes(in); if (array == null) return null; if (!is_compressed) { return array; } try { ByteArrayInputStream bais = new ByteArrayInputStream(array); GZIPInputStream gzin = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); IOUtils.copyTo(gzin, baos); gzin.close(); bais.close(); return baos.toByteArray(); } catch (IOException err) { throw new RuntimeException(err); } }
|
11
|
Code Sample 1:
private String load(URL url) { BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); while (r.ready()) { buf.append(r.readLine()).append('\n'); } r.close(); return buf.toString(); } catch (IOException e) { e.printStackTrace(); return null; } }
Code Sample 2:
public static Map<String, String> getInstanceMetadata() { HashMap<String, String> result = new HashMap<String, String>(); int retries = 0; while (true) { try { URL url = new URL("http://169.254.169.254/latest/meta-data/"); BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream())); String line = rdr.readLine(); while (line != null) { try { String val = getInstanceMetadata(line); result.put(line, val); } catch (IOException ex) { logger.error("Problem fetching piece of instance metadata!", ex); } line = rdr.readLine(); } return result; } catch (IOException ex) { if (retries == 5) { logger.debug("Problem getting instance data, retries exhausted..."); return result; } else { logger.debug("Problem getting instance data, retrying..."); try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException e) { } retries++; } } } }
|
11
|
Code Sample 1:
public static String getMD5HashFromString(String message) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(message.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
Code Sample 2:
public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
|
11
|
Code Sample 1:
@Override public T[] sort(T[] values) { super.compareTimes = 0; for (int i = 0; i < values.length; i++) { for (int j = 0; j < values.length - i - 1; j++) { super.compareTimes++; if (values[j].compareTo(values[j + 1]) > 0) { T temp = values[j]; values[j] = values[j + 1]; values[j + 1] = temp; } } } return values; }
Code Sample 2:
public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); }
|
11
|
Code Sample 1:
public static File createGzip(File inputFile) { File targetFile = new File(inputFile.getParentFile(), inputFile.getName() + ".gz"); if (targetFile.exists()) { log.warn("The target file '" + targetFile + "' already exists. Will overwrite"); } FileInputStream in = null; GZIPOutputStream out = null; try { int read = 0; byte[] data = new byte[BUFFER_SIZE]; in = new FileInputStream(inputFile); out = new GZIPOutputStream(new FileOutputStream(targetFile)); while ((read = in.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, read); } in.close(); out.close(); boolean deleteSuccess = inputFile.delete(); if (!deleteSuccess) { log.warn("Could not delete file '" + inputFile + "'"); } log.info("Successfully created gzip file '" + targetFile + "'."); } catch (Exception e) { log.error("Exception while creating GZIP.", e); } finally { StreamUtil.tryCloseStream(in); StreamUtil.tryCloseStream(out); } return targetFile; }
Code Sample 2:
public byte[] getFile(final String file) throws IOException { if (this.files.contains(file)) { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if ((entry.getName().equals(file)) && (!entry.isDirectory())) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(input, output); output.close(); input.close(); return output.toByteArray(); } } input.close(); } return null; }
|
00
|
Code Sample 1:
private void loadRDFURL(URL url) throws RDFParseException, RepositoryException { URI urlContext = valueFactory.createURI(url.toString()); try { URLConnection urlConn = url.openConnection(); urlConn.setRequestProperty("Accept", "application/rdf+xml"); InputStream is = urlConn.getInputStream(); repoConn.add(is, url.toString(), RDFFormat.RDFXML, urlContext); is.close(); repoConn.commit(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void copyFile(String input, String output) { try { File inputFile = new File(input); File outputFile = new File(output); FileReader in; 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 e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static boolean downloadFile(String srcUri, String srcDest) { try { URL url = new URL(srcUri); InputStream is = url.openStream(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(srcDest)); byte[] buff = new byte[10000]; int b; while ((b = is.read(buff)) > 0) bos.write(buff, 0, b); is.close(); bos.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("H:\\FileServeUploader.java"); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", langcookie + ";" + sessioncookie + ";" + mailcookie + ";" + namecookie + ";" + rolecookie + ";" + orderbycookie + ";" + directioncookie + ";"); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("files[]", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into wupload..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); }
|
00
|
Code Sample 1:
public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
void getAddress(String lat, String lag) { try { URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q=" + lat + "," + lag); InputStream inputStream = url.openConnection().getInputStream(); InputStreamReader inputReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufReader = new BufferedReader(inputReader); String line = "", lines = ""; while ((line = bufReader.readLine()) != null) { lines += line; } if (!lines.equals("")) { JSONObject jsonobject = new JSONObject(lines); JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString()); for (int i = 0; i < jsonArray.length(); i++) { mTextView.setText(mTextView.getText() + "\n" + jsonArray.getJSONObject(i).getString("address")); } } } catch (Exception e) { ; } }
|
00
|
Code Sample 1:
private static String getDigest(String srcStr, String alg) { Assert.notNull(srcStr); Assert.notNull(alg); try { MessageDigest alga = MessageDigest.getInstance(alg); alga.update(srcStr.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public String sruRead(String initialURL) { out('\n'); out(" trying: "); out(initialURL); out('\n'); numTests++; URL url = null; try { url = new URL(initialURL); } catch (java.net.MalformedURLException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentType = huc.getContentType(); if (contentType == null || (contentType.indexOf("text/xml") < 0 && contentType.indexOf("application/xml") < 0)) { out(" ** Warning: Content-Type not set to text/xml or application/xml"); out('\n'); out(" Content-type: "); out(contentType); out('\n'); numWarns++; } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: opening URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading first line of response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine == null) { out("</pre><pre class='red'>"); out("test failed: No input read from URL"); out('\n'); out("</pre><pre>"); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); while (inputLine.length() == 0) inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine.startsWith("<?xml-stylesheet ")) { offset = inputLine.indexOf("href="); href = (inputLine.substring(inputLine.indexOf("href=") + 6)); href = href.substring(0, href.indexOf('"')); transformer = (Transformer) transformers.get(href); if (stylesheets.get(href) == null) try { out(" reading stylesheet: "); out(href); out('\n'); out(" from source: "); out(url.toString()); out('\n'); StreamSource source = new StreamSource(url.toString()); TransformerFactory tFactory = TransformerFactory.newInstance(); Source stylesht = tFactory.getAssociatedStylesheet(source, null, null, null); transformer = tFactory.newTransformer(stylesht); transformers.put(href, transformer); } catch (Exception e) { e.printStackTrace(); out("</pre><pre class='red'>"); out("unable to load stylesheet: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); } stylesheets.put(href, href); } else content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); out(" successfully applied stylesheet '"); out(href); out("'"); out('\n'); } catch (javax.xml.transform.TransformerException e) { out("</pre><pre class='red'>"); out("unable to apply stylesheet '"); out(href); out("'to response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); e.printStackTrace(); } } return contentStr; }
|
11
|
Code Sample 1:
public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
Code Sample 2:
public static void main(String[] args) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); String text = "YUMyfj"; md.update(text.getBytes(), 0, text.length()); System.out.println(new BigInteger(1, md.digest()).toString(16).toString()); }
|
11
|
Code Sample 1:
private void zip(FileHolder fileHolder, int zipCompressionLevel) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File zipDestFile = new File(fileHolder.destFiles[0]); try { ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile)); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); ZipEntry entry = new ZipEntry(selectedFile.getName()); outStream.setLevel(zipCompressionLevel); outStream.putNextEntry(entry); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.closeEntry(); this.inStream.close(); } outStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error zipping: " + zipDestFile); logger.logError(errEntry); } return; }
Code Sample 2:
private void loadInitialDbState() throws IOException { InputStream in = SchemaAndDataPopulator.class.getClassLoader().getResourceAsStream(resourceName); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer); for (String statement : writer.toString().split(SQL_STATEMENT_DELIMITER)) { logger.info("Executing SQL Statement {}", statement); template.execute(statement); } }
|
00
|
Code Sample 1:
public Properties load() { Properties lvProperties = new Properties(); try { InputStream lvInputStream = url.openStream(); lvProperties.load(lvInputStream); } catch (Exception e) { throw new PropertiesLoadException("Error in load-method:", e); } return lvProperties; }
Code Sample 2:
private void copy(String url, File toDir) throws IOException { System.err.println("url=" + url + " dir=" + toDir); if (url.endsWith("/")) { String basename = url.substring(url.lastIndexOf("/", url.length() - 2) + 1); File directory = new File(toDir, basename); directory.mkdir(); LineNumberReader reader = new LineNumberReader(new InputStreamReader(new URL(url).openStream(), "utf-8")); String line; while ((line = reader.readLine()) != null) { System.err.println(line.replace('\t', '|')); int tab = line.lastIndexOf('\t', line.lastIndexOf('\t', line.lastIndexOf('\t') - 1) - 1); System.err.println(tab); char type = line.charAt(tab + 1); String file = line.substring(0, tab); copy(url + URIUtil.encodePath(file) + (type == 'd' ? "/" : ""), directory); } } else { String basename = url.substring(url.lastIndexOf("/") + 1); File file = new File(toDir, basename); System.err.println("copy " + url + " --> " + file); IO.copy(new URL(url).openStream(), new FileOutputStream(file)); } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void read(Model model, String url) { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) { read(model, conn.getInputStream(), url); } else { read(model, new InputStreamReader(conn.getInputStream(), encoding), url); } } catch (IOException e) { throw new JenaException(e); } }
|
00
|
Code Sample 1:
protected void load() throws IOException { for (ClassLoader classLoader : classLoaders) { Enumeration<URL> en = classLoader.getResources("META-INF/services/" + serviceClass.getName()); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStream in = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); try { String line = null; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { line = line.trim(); if (line.length() > 0) contributions.add(resolveClass(url, line)); } } } finally { reader.close(); } } finally { in.close(); } } } }
Code Sample 2:
public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
|
11
|
Code Sample 1:
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; }
Code Sample 2:
public void render(HttpServletRequest request, HttpServletResponse response, File file, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } if (file.length() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Cannot send file greater than 2GB"); } response.setContentLength((int) file.length()); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); }
|
11
|
Code Sample 1:
public void performOk(final IProject project, final TomcatPropertyPage page) { page.setPropertyValue("tomcat.jdbc.driver", c_drivers.getText()); page.setPropertyValue("tomcat.jdbc.url", url.getText()); page.setPropertyValue("tomcat.jdbc.user", username.getText()); page.setPropertyValue("tomcat.jdbc.password", password.getText()); File lib = new File(page.tomcatHome.getText(), "lib"); if (!lib.exists()) { lib = new File(new File(page.tomcatHome.getText(), "common"), "lib"); if (!lib.exists()) { Logger.log(Logger.ERROR, "Not properly location of Tomcat Home at :: " + lib); throw new IllegalStateException("Not properly location of Tomcat Home"); } } final File conf = new File(page.tomcatHome.getText(), "conf/Catalina/localhost"); if (!conf.exists()) { final boolean create = NexOpenUIActivator.getDefault().getTomcatConfProperty(); if (create) { if (Logger.getLog().isDebugEnabled()) { Logger.getLog().debug("Create directory " + conf); } try { conf.mkdirs(); } catch (final SecurityException se) { Logger.getLog().error("Retrieved a Security exception creating " + conf, se); Logger.log(Logger.ERROR, "Not created " + conf + " directory. Not enough privilegies. Message :: " + se.getMessage()); } } } String str_driverLibrary = LIBRARIES.get(c_drivers.getText()); if ("<mysql_driver>".equals(str_driverLibrary)) { str_driverLibrary = NexOpenUIActivator.getDefault().getMySQLDriver(); } final File driverLibrary = new File(lib, str_driverLibrary); if (!driverLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + str_driverLibrary)); fos = new FileOutputStream(driverLibrary); IOUtils.copy(driver, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the driver jar file to Tomcat", e); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } page.processTomcatCfg(c_drivers.getText(), url.getText(), username.getText(), password.getText()); }
Code Sample 2:
private void copyJdbcDriverToWL(final WLPropertyPage page) { final File url = new File(page.getDomainDirectory()); final File lib = new File(url, "lib"); final File mysqlLibrary = new File(lib, NexOpenUIActivator.getDefault().getMySQLDriver()); if (!mysqlLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + NexOpenUIActivator.getDefault().getMySQLDriver())); fos = new FileOutputStream(mysqlLibrary); IOUtils.copy(driver, fos); } catch (final IOException e) { Logger.log(Logger.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); final Status status = new Status(Status.ERROR, NexOpenUIActivator.PLUGIN_ID, Status.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); ErrorDialog.openError(page.getShell(), "Bea WebLogic MSQL support", "Could not copy the MySQL Driver jar file to Bea WL", status); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } }
|
11
|
Code Sample 1:
public static final void parse(String infile, String outfile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(infile)); DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile)); int w = Integer.parseInt(reader.readLine()); int h = Integer.parseInt(reader.readLine()); output.writeByte(w); output.writeByte(h); int lineCount = 2; try { do { for (int i = 0; i < h; i++) { lineCount++; String line = reader.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of file at line " + lineCount); } for (int j = 0; j < w; j++) { char c = line.charAt(j); System.out.print(c); output.writeByte(c); } System.out.println(""); } lineCount++; output.writeShort(Short.parseShort(reader.readLine())); } while (reader.readLine() != null); } finally { reader.close(); output.close(); } }
Code Sample 2:
private void doTask() { try { log("\n\n\n\n\n\n\n\n\n"); log(" ================================================="); log(" = Starting PSCafePOS ="); log(" ================================================="); log(" = An open source point of sale system ="); log(" = for educational organizations. ="); log(" ================================================="); log(" = General Information ="); log(" = http://pscafe.sourceforge.net ="); log(" = Free Product Support ="); log(" = http://www.sourceforge.net/projects/pscafe ="); log(" ================================================="); log(" = License Overview ="); log(" ================================================="); log(" = PSCafePOS is a POS System for Schools ="); log(" = Copyright (C) 2007 Charles Syperski ="); log(" = ="); log(" = This program is free software; you can ="); log(" = redistribute it and/or modify it under the ="); log(" = terms of the GNU General Public License as ="); log(" = published by the Free Software Foundation; ="); log(" = either version 2 of the License, or any later ="); log(" = version. ="); log(" = ="); log(" = This program is distributed in the hope that ="); log(" = it will be useful, but WITHOUT ANY WARRANTY; ="); log(" = without even the implied warranty of ="); log(" = MERCHANTABILITY or FITNESS FOR A PARTICULAR ="); log(" = PURPOSE. ="); log(" = ="); log(" = See the GNU General Public License for more ="); log(" = details. ="); log(" = ="); log(" = You should have received a copy of the GNU ="); log(" = General Public License along with this ="); log(" = program; if not, write to the ="); log(" = ="); log(" = Free Software Foundation, Inc. ="); log(" = 59 Temple Place, Suite 330 ="); log(" = Boston, MA 02111-1307 USA ="); log(" ================================================="); log(" = If you have any questions of comments please ="); log(" = let us know at http://pscafe.sourceforge.net ="); log(" ================================================="); pause(); File settings; if (blAltSettings) { System.out.println("\n + Alternative path specified at run time:"); System.out.println(" Path: " + strAltPath); settings = new File(strAltPath); } else { settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Checking for existance of settings..."); boolean blGo = false; if (settings.exists() && settings.canRead()) { log("[OK]"); blGo = true; if (forceConfig) { System.out.print("\n + Running Config Wizard (at user request)..."); Process pp = Runtime.getRuntime().exec("java -cp . PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = pp.getErrorStream(); InputStream stdin = pp.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); pp.waitFor(); } } else { log("[FAILED]"); settings = new File("etc" + File.separatorChar + "settings.dbp.firstrun"); System.out.print("\n + Checking if this is the first run... "); if (settings.exists() && settings.canRead()) { log("[FOUND]"); File toFile = new File("etc" + File.separatorChar + "settings.dbp"); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(settings); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } if (toFile.exists() && toFile.canRead()) { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Running Settings Wizard... "); try { Process p = Runtime.getRuntime().exec("java PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = p.getErrorStream(); InputStream stdin = p.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); p.waitFor(); log("[OK]"); if (p.exitValue() == 0) blGo = true; } catch (InterruptedException i) { System.err.println(i.getMessage()); } } catch (Exception ex) { System.err.println(ex.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } else { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); DBSettingsWriter writ = new DBSettingsWriter(); writ.writeFile(new DBSettings(), settings); blGo = true; } } if (blGo) { String cp = "."; try { File classpath = new File("lib"); File[] subFiles = classpath.listFiles(); for (int i = 0; i < subFiles.length; i++) { if (subFiles[i].isFile()) { cp += File.pathSeparatorChar + "lib" + File.separatorChar + subFiles[i].getName() + ""; } } } catch (Exception e) { System.err.println(e.getMessage()); } try { boolean blExecutePOS = false; System.out.print("\n + Checking runtime settings... "); DBSettings info = null; if (settings == null) settings = new File("etc" + File.separatorChar + "settings.dbp"); if (settings.exists() && settings.canRead()) { DBSettingsWriter writ = new DBSettingsWriter(); info = (DBSettings) writ.loadSettingsDB(settings); if (info != null) { blExecutePOS = true; } } if (blExecutePOS) { log("[OK]"); String strSSL = ""; String strSSLDebug = ""; if (info != null) { debug = info.get(DBSettings.MAIN_DEBUG).compareTo("1") == 0; if (debug) log(" * Debug Mode is ON"); else log(" * Debug Mode is OFF"); if (info.get(DBSettings.POS_SSLENABLED).compareTo("1") == 0) { strSSL = "-Djavax.net.ssl.keyStore=" + info.get(DBSettings.POS_SSLKEYSTORE) + " -Djavax.net.ssl.keyStorePassword=pscafe -Djavax.net.ssl.trustStore=" + info.get(DBSettings.POS_SSLTRUSTSTORE) + " -Djavax.net.ssl.trustStorePassword=pscafe"; log(" * Using SSL"); debug(" " + strSSL); if (info.get(DBSettings.POS_SSLDEBUG).compareTo("1") == 0) { strSSLDebug = "-Djavax.net.debug=all"; log(" * SSL Debugging enabled"); debug(" " + strSSLDebug); } } } String strPOSRun = "java -cp " + cp + " " + strSSL + " " + strSSLDebug + " POSDriver " + settings.getPath(); debug(strPOSRun); System.out.print("\n + Running PSCafePOS... "); Process pr = Runtime.getRuntime().exec(strPOSRun); System.out.print("[OK]\n\n"); InputStream stderr = pr.getErrorStream(); InputStream stdin = pr.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); InputStreamReader isre = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); BufferedReader bre = new BufferedReader(isre); String line = null; String lineError = null; log(" ================================================="); log(" = Output from PSCafePOS System ="); log(" ================================================="); while ((line = br.readLine()) != null || (lineError = bre.readLine()) != null) { if (line != null) System.out.println(" [PSCafePOS]" + line); if (lineError != null) System.out.println(" [ERR]" + lineError); } pr.waitFor(); log(" ================================================="); log(" = End output from PSCafePOS System ="); log(" = PSCafePOS has exited ="); log(" ================================================="); } else { log("[Failed]"); } } catch (Exception i) { log(i.getMessage()); i.printStackTrace(); } } } catch (Exception e) { log(e.getMessage()); } }
|
00
|
Code Sample 1:
public static void main(String[] args) { JFileChooser askDir = new JFileChooser(); askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); askDir.setMultiSelectionEnabled(false); int returnVal = askDir.showOpenDialog(null); if (returnVal == JFileChooser.CANCEL_OPTION) { System.exit(returnVal); } File startDir = askDir.getSelectedFile(); ArrayList<File> files = new ArrayList<File>(); goThrough(startDir, files); SearchClient client = new SearchClient("VZFo5W5i"); MyID3 singleton = new MyID3(); for (File song : files) { try { MusicMetadataSet set = singleton.read(song); IMusicMetadata meta = set.getSimplified(); String qu = song.getName(); if (meta.getAlbum() != null) { qu = meta.getAlbum(); } else if (meta.getArtist() != null) { qu = meta.getArtist(); } if (qu.length() > 2) { ImageSearchRequest req = new ImageSearchRequest(qu); ImageSearchResults res = client.imageSearch(req); if (res.getTotalResultsAvailable().doubleValue() > 1) { System.out.println("Downloading " + res.listResults()[0].getUrl()); URL url = new URL(res.listResults()[0].getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); int realSize = con.getContentLength(); if (realSize > 0) { String mime = con.getContentType(); InputStream stream = con.getInputStream(); byte[] realData = new byte[realSize]; for (int i = 0; i < realSize; i++) { stream.read(realData, i, 1); } stream.close(); ImageData imgData = new ImageData(realData, mime, qu, 0); meta.addPicture(imgData); File temp = File.createTempFile("tempsong", "mp3"); singleton.write(song, temp, set, meta); FileChannel inChannel = new FileInputStream(temp).getChannel(); FileChannel outChannel = new FileOutputStream(song).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } temp.delete(); } } } } catch (ID3ReadException e) { } catch (MalformedURLException e) { } catch (UnsupportedEncodingException e) { } catch (ID3WriteException e) { } catch (IOException e) { } catch (SearchException e) { } } }
Code Sample 2:
private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException { URL wsdlurl = null; try { wsdlurl = new URL(uri); } catch (MalformedURLException e) { return new InputSource(uri); } if (username == null && wsdlurl.getUserInfo() == null) { return new InputSource(uri); } if (!wsdlurl.getProtocol().startsWith("http")) { return new InputSource(uri); } URLConnection connection = wsdlurl.openConnection(); if (!(connection instanceof HttpURLConnection)) { return new InputSource(uri); } HttpURLConnection uconn = (HttpURLConnection) connection; String userinfo = wsdlurl.getUserInfo(); uconn.setRequestMethod("GET"); uconn.setAllowUserInteraction(false); uconn.setDefaultUseCaches(false); uconn.setDoInput(true); uconn.setDoOutput(false); uconn.setInstanceFollowRedirects(true); uconn.setUseCaches(false); String auth = null; if (userinfo != null) { auth = userinfo; } else if (username != null) { auth = (password == null) ? username : username + ":" + password; } if (auth != null) { uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(charEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); }
|
00
|
Code Sample 1:
public static Bitmap loadPhotoBitmap(final String imageUrl, final String type) { InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; }
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); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
Code Sample 2:
public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.