label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static boolean copyFile(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; boolean retour = false; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); retour = true; } catch (IOException e) { System.err.println("File : " + fileIn); e.printStackTrace(); } return retour; } Code Sample 2: public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: java SOAPClient4XG " + "http://soapURL soapEnvelopefile.xml" + " [SOAPAction]"); System.err.println("SOAPAction is optional."); System.exit(1); } String SOAPUrl = args[0]; String xmlFile2Send = args[1]; String SOAPAction = ""; if (args.length > 2) SOAPAction = args[2]; URL url = new URL(SOAPUrl); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }
00
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 (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } } Code Sample 2: public static void exportDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = input + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); HashMap<Integer, String> languageIDs = new HashMap<Integer, String>(); HashMap<Integer, String> typeIDs = new HashMap<Integer, String>(); long tiempoInicio = System.currentTimeMillis(); Element dataBaseXML = new Element("database"); Element languages = new Element("languages"); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select * from language order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); languageIDs.put(id, name); Element language = new Element("language"); language.setText(name); languages.addContent(language); } dataBaseXML.addContent(languages); rs = stat.executeQuery("select * from type order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); typeIDs.put(id, name); } rs = stat.executeQuery("select distinct name from main order by name"); while (rs.next()) { String name = rs.getString("name"); Element image = new Element("image"); image.setAttribute("id", name); Statement stat2 = G.conn.createStatement(); ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL"); while (rs2.next()) { int idL = rs2.getInt("idL"); Element language = new Element("language"); language.setAttribute("id", languageIDs.get(idL)); Statement stat3 = G.conn.createStatement(); ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT"); while (rs3.next()) { int idT = rs3.getInt("idT"); String word = rs3.getString("word"); Element wordE = new Element("word"); wordE.setAttribute("type", typeIDs.get(idT)); wordE.setText(word); language.addContent(wordE); String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name; String pathDst = output + File.separator + name; 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.getMessage()); System.out.println(exc.toString()); } } rs3.close(); stat3.close(); image.addContent(language); } rs2.close(); stat2.close(); dataBaseXML.addContent(image); } rs.close(); stat.close(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName); out.output(dataBaseXML, f); f.flush(); f.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static Pedido insert(Pedido objPedido) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; if (c == null) { return null; } try { c.setAutoCommit(false); String sql = ""; int idPedido; idPedido = PedidoDAO.getLastCodigo(); if (idPedido < 1) { return null; } sql = "insert into pedido " + "(id_pedido, id_funcionario,data_pedido,valor) " + "values(?,?,now(),truncate(?,2))"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, objPedido.getFuncionario().getCodigo()); pst.setString(3, new DecimalFormat("#0.00").format(objPedido.getValor())); result = pst.executeUpdate(); pst = null; if (result > 0) { Iterator<ItemPedido> itItemPedido = (objPedido.getItemPedido()).iterator(); while ((itItemPedido != null) && (itItemPedido.hasNext())) { ItemPedido objItemPedido = (ItemPedido) itItemPedido.next(); sql = ""; sql = "insert into item_pedido " + "(id_pedido,id_produto,quantidade,subtotal) " + "values (?,?,?,truncate(?,2))"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, (objItemPedido.getProduto()).getCodigo()); pst.setInt(3, objItemPedido.getQuantidade()); pst.setString(4, new DecimalFormat("#0.00").format(objItemPedido.getSubtotal())); result = pst.executeUpdate(); } } pst = null; sql = ""; sql = "insert into pedido_situacao " + "(id_pedido,id_situacao, em, observacao, id_funcionario) " + "values (?,?,now(), ?, ?)"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, 1); pst.setString(3, "Inclus�o de pedido"); pst.setInt(4, objPedido.getFuncionario().getCodigo()); result = pst.executeUpdate(); pst = null; sql = ""; sql = "insert into tramitacao " + "(data_tramitacao, id_pedido, id_dep_origem, id_dep_destino) " + "values (now(),?,?, ?)"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, 6); pst.setInt(3, 2); result = pst.executeUpdate(); c.commit(); objPedido.setCodigo(idPedido); } catch (final Exception e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } return objPedido; } Code Sample 2: public static boolean insert(final Departamento ObjDepartamento) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, ObjDepartamento.getNome()); pst.setString(2, ObjDepartamento.getSala()); pst.setString(3, ObjDepartamento.getTelefone()); pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); EntityManager em = EMF.get().createEntityManager(); String url = req.getRequestURL().toString(); String key = req.getParameter("key"); String format = req.getParameter("format"); if (key == null || !key.equals(Keys.APPREGKEY)) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (format != null && format.equals("xml")) resp.getWriter().print(Error.notAuthorised("").toXML(em)); else resp.getWriter().print(Error.notAuthorised("").toJSON(em)); em.close(); return; } String appname = req.getParameter("name"); if (appname == null || appname.equals("")) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.noAppId(null).toXML(em)); else resp.getWriter().print(Error.noAppId(null).toJSON(em)); em.close(); return; } StringBuffer appkey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + appname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { appkey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } ClientApp app = new ClientApp(); app.setName(appname); app.setKey(appkey.toString()); app.setNumreceipts(0L); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(app); tx.commit(); } catch (Throwable t) { log.severe("Error persisting application " + app.getName() + ": " + t.getMessage()); tx.rollback(); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); em.close(); return; } resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(app.toXML(em)); else resp.getWriter().print(app.toJSON(em)); em.close(); }
11
Code Sample 1: public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm�nye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut�s sor�n hiba t�rt�nt!"); } } } Code Sample 2: private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
11
Code Sample 1: private String signMethod() { String str = API.SHARED_SECRET; Vector<String> v = new Vector<String>(parameters.keySet()); Collections.sort(v); for (String key : v) { str += key + parameters.get(key); } MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); m.update(str.getBytes(), 0, str.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public static String encrypt(String unencryptedString) { if (StringUtils.isBlank(unencryptedString)) { throw new IllegalArgumentException("Cannot encrypt a null or empty string"); } MessageDigest md = null; String encryptionAlgorithm = Environment.getValue(Environment.PROP_ENCRYPTION_ALGORITHM); try { md = MessageDigest.getInstance(encryptionAlgorithm); } catch (NoSuchAlgorithmException e) { logger.warn("JDK does not support the " + encryptionAlgorithm + " encryption algorithm. Weaker encryption will be attempted."); } if (md == null) { try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException("JDK does not support the SHA-1 or SHA-512 encryption algorithms"); } Environment.setValue(Environment.PROP_ENCRYPTION_ALGORITHM, "SHA-1"); try { Environment.saveConfiguration(); } catch (WikiException e) { logger.info("Failure while saving encryption algorithm property", e); } } try { md.update(unencryptedString.getBytes("UTF-8")); byte raw[] = md.digest(); return encrypt64(raw); } catch (GeneralSecurityException e) { logger.error("Encryption failure", e); throw new IllegalStateException("Failure while encrypting value"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Unsupporting encoding UTF-8"); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } }
11
Code Sample 1: public void run(Preprocessor pp) throws SijappException { for (int i = 0; i < this.filenames.length; i++) { File srcFile = new File(this.srcDir, this.filenames[i]); BufferedReader reader; try { InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile), "CP1251"); reader = new BufferedReader(isr); } catch (Exception e) { throw (new SijappException("File " + srcFile.getPath() + " could not be read")); } File destFile = new File(this.destDir, this.filenames[i]); BufferedWriter writer; try { (new File(destFile.getParent())).mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile), "CP1251"); writer = new BufferedWriter(osw); } catch (Exception e) { throw (new SijappException("File " + destFile.getPath() + " could not be written")); } try { pp.run(reader, writer); } catch (SijappException e) { try { reader.close(); } catch (IOException f) { } try { writer.close(); } catch (IOException f) { } try { destFile.delete(); } catch (SecurityException f) { } throw (new SijappException(srcFile.getPath() + ":" + e.getMessage())); } try { reader.close(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } } Code Sample 2: public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
00
Code Sample 1: private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; } Code Sample 2: public static List<ReactomeBean> getUrlData(URL url) throws IOException { List<ReactomeBean> beans = new ArrayList<ReactomeBean>(256); log.debug("Retreiving content for: " + url); StringBuffer content = new StringBuffer(4096); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.startsWith("#")) { continue; } StringTokenizer stringTokenizer = new StringTokenizer(str, "\t"); String InteractionAc = stringTokenizer.nextToken(); String reactomeId = stringTokenizer.nextToken(); ReactomeBean reactomeBean = new ReactomeBean(); reactomeBean.setReactomeID(reactomeId); reactomeBean.setInteractionAC(InteractionAc); beans.add(reactomeBean); } in.close(); return beans; }
00
Code Sample 1: public Ontology open(String resource_name) { Ontology ontology = null; try { URL url = null; if (resource_name.startsWith("jar")) url = new URL(resource_name); else { ClassLoader cl = this.getClass().getClassLoader(); url = cl.getResource(resource_name); } InputStream input_stream; if (url != null) { JarURLConnection jc = (JarURLConnection) url.openConnection(); input_stream = jc.getInputStream(); } else input_stream = new FileInputStream(resource_name); ObjectInputStream ois = new ObjectInputStream(input_stream); ontology = (Ontology) ois.readObject(); ois.close(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return ontology; } Code Sample 2: protected static void createBackup() throws IOException, IllegalStateException, FTPIllegalReplyException, FTPException, FileNotFoundException, FTPDataTransferException, FTPAbortedException { String cmd = "mysqldump -u " + Constants.dbUser + " -p" + Constants.dbPassword + " " + Constants.dbName + " > " + Constants.tmpDir + "Backup.sql"; FileWriter fstream = new FileWriter(Constants.tmpDir + Constants.tmpScript); BufferedWriter out = new BufferedWriter(fstream); out.write(cmd); out.close(); Process process = Runtime.getRuntime().exec(Constants.tmpDir + Constants.tmpScript); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (br.readLine() != null) { ; } String fileName = now4backup(); cmd = "\"C:\\Archivos de programa\\WinRAR\\Rar.exe\" a -m5 -ed " + Constants.tmpDir + fileName + " " + Constants.tmpDir + "Backup.sql"; process = Runtime.getRuntime().exec(cmd); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while (br.readLine() != null) { ; } FTPClient client = new FTPClient(); client.connect(Constants.ftpBackupAddr); client.login(Constants.ftpBackupUser, Constants.ftpBackupPassword); client.changeDirectory("/" + Shared.getConfig("storeName")); File f = new File(Constants.tmpDir + fileName); client.upload(f); client.disconnect(false); }
11
Code Sample 1: public synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); MailSetting tmpMailSetting = (MailSetting) ((MailSetting) obj).clone(); synchronized (dbConn) { try { int updateCnt = 0; Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("UPDATE MAIL_SETTING "); sqlStat.append("SET USER_RECORD_ID=?, PROFILE_NAME=?, MAIL_SERVER_TYPE=?, DISPLAY_NAME=?, EMAIL_ADDRESS=?, REMEMBER_PWD_FLAG=?, SPA_LOGIN_FLAG=?, INCOMING_SERVER_HOST=?, INCOMING_SERVER_PORT=?, INCOMING_SERVER_LOGIN_NAME=?, INCOMING_SERVER_LOGIN_PWD=?, OUTGOING_SERVER_HOST=?, OUTGOING_SERVER_PORT=?, OUTGOING_SERVER_LOGIN_NAME=?, OUTGOING_SERVER_LOGIN_PWD=?, PARAMETER_1=?, PARAMETER_2=?, PARAMETER_3=?, PARAMETER_4=?, PARAMETER_5=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? "); sqlStat.append("WHERE ID=? AND UPDATE_COUNT=? "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, tmpMailSetting.getUserRecordID()); setPrepareStatement(preStat, 2, tmpMailSetting.getProfileName()); setPrepareStatement(preStat, 3, tmpMailSetting.getMailServerType()); setPrepareStatement(preStat, 4, tmpMailSetting.getDisplayName()); setPrepareStatement(preStat, 5, tmpMailSetting.getEmailAddress()); setPrepareStatement(preStat, 6, tmpMailSetting.getRememberPwdFlag()); setPrepareStatement(preStat, 7, tmpMailSetting.getSpaLoginFlag()); setPrepareStatement(preStat, 8, tmpMailSetting.getIncomingServerHost()); setPrepareStatement(preStat, 9, tmpMailSetting.getIncomingServerPort()); setPrepareStatement(preStat, 10, tmpMailSetting.getIncomingServerLoginName()); setPrepareStatement(preStat, 11, tmpMailSetting.getIncomingServerLoginPwd()); setPrepareStatement(preStat, 12, tmpMailSetting.getOutgoingServerHost()); setPrepareStatement(preStat, 13, tmpMailSetting.getOutgoingServerPort()); setPrepareStatement(preStat, 14, tmpMailSetting.getOutgoingServerLoginName()); setPrepareStatement(preStat, 15, tmpMailSetting.getOutgoingServerLoginPwd()); setPrepareStatement(preStat, 16, tmpMailSetting.getParameter1()); setPrepareStatement(preStat, 17, tmpMailSetting.getParameter2()); setPrepareStatement(preStat, 18, tmpMailSetting.getParameter3()); setPrepareStatement(preStat, 19, tmpMailSetting.getParameter4()); setPrepareStatement(preStat, 20, tmpMailSetting.getParameter5()); setPrepareStatement(preStat, 21, new Integer(tmpMailSetting.getUpdateCount().intValue() + 1)); setPrepareStatement(preStat, 22, sessionContainer.getUserRecordID()); setPrepareStatement(preStat, 23, currTime); setPrepareStatement(preStat, 24, tmpMailSetting.getID()); setPrepareStatement(preStat, 25, tmpMailSetting.getUpdateCount()); updateCnt = preStat.executeUpdate(); dbConn.commit(); if (updateCnt == 0) { throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR); } else { tmpMailSetting.setUpdaterID(sessionContainer.getUserRecordID()); tmpMailSetting.setUpdateDate(currTime); tmpMailSetting.setUpdateCount(new Integer(tmpMailSetting.getUpdateCount().intValue() + 1)); tmpMailSetting.setCreatorName(UserInfoFactory.getUserFullName(tmpMailSetting.getCreatorID())); tmpMailSetting.setUpdaterName(UserInfoFactory.getUserFullName(tmpMailSetting.getUpdaterID())); return (tmpMailSetting); } } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ex) { } log.error(e, e); throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } } Code Sample 2: public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); }
00
Code Sample 1: private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); } Code Sample 2: public void run() { try { URL url = new URL("http://mydiversite.appspot.com/version.html"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public 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: public void moveRuleDown(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt, language, tag); if ((row < 1) || (row > (max - 1))) throw new IllegalArgumentException("Row number (" + row + ") was not between 1 and " + (max - 1)); stmt.executeUpdate("update LanguageMorphologies set Rank = -1 " + "where Rank = " + row + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + row + "where Rank = " + (row + 1) + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + (row + 1) + "where Rank = -1 and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
00
Code Sample 1: private void parseExternalCss(Document d) throws XPathExpressionException, IOException { InputStream is = null; try { XPath xp = xpf.newXPath(); XPathExpression xpe = xp.compile("//link[@type='text/css']/@href"); NodeList nl = (NodeList) xpe.evaluate(d, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Attr a = (Attr) nl.item(i); String url = a.getValue(); URL u = new URL(url); is = new BufferedInputStream(u.openStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); parser.add(new String(baos.toByteArray(), "UTF-8")); Element linkNode = a.getOwnerElement(); Element parent = (Element) linkNode.getParentNode(); parent.removeChild(linkNode); IOUtils.closeQuietly(is); is = null; } } finally { IOUtils.closeQuietly(is); } } Code Sample 2: public URLConnection makeURLConnection(String server) throws IOException { if (server == null) { connection = null; } else { URL url = new URL("http://" + server + "/Bob/QueryXindice"); connection = url.openConnection(); connection.setDoOutput(true); } return connection; }
11
Code Sample 1: public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
00
Code Sample 1: public MoteDeploymentConfiguration addMoteDeploymentConfiguration(int projectDepConfID, int moteID, int programID, int radioPowerLevel) throws AdaptationException { MoteDeploymentConfiguration mdc = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO MoteDeploymentConfigurations(" + "projectDeploymentConfigurationID, " + "moteID, programID, radioPowerLevel) VALUES (" + projectDepConfID + ", " + moteID + ", " + programID + ", " + radioPowerLevel + ")"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from MoteDeploymentConfigurations WHERE " + "projectDeploymentConfigurationID = " + projectDepConfID + " AND moteID = " + moteID; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Unable to select newly added config."; log.error(msg); ; throw new AdaptationException(msg); } mdc = getMoteDeploymentConfiguration(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in addMoteDeploymentConfiguration"; 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 mdc; } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
11
Code Sample 1: public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
00
Code Sample 1: public HttpUrlConnectionCall(HttpClientHelper helper, String method, String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); if (requestUri.startsWith("http")) { URL url = new URL(requestUri); this.connection = (HttpURLConnection) url.openConnection(); int majorVersionNumber = Engine.getJavaMajorVersion(); int minorVersionNumber = Engine.getJavaMinorVersion(); if ((majorVersionNumber > 1) || (majorVersionNumber == 1 && minorVersionNumber >= 5)) { this.connection.setConnectTimeout(getHelper().getConnectTimeout()); this.connection.setReadTimeout(getHelper().getReadTimeout()); } this.connection.setAllowUserInteraction(getHelper().isAllowUserInteraction()); this.connection.setDoOutput(hasEntity); this.connection.setInstanceFollowRedirects(getHelper().isFollowRedirects()); this.connection.setUseCaches(getHelper().isUseCaches()); this.responseHeadersAdded = false; setConfidential(this.connection instanceof HttpsURLConnection); } else { throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here"); } } Code Sample 2: private List<String> getSignatureResourceNames(URL url) throws IOException, ParserConfigurationException, SAXException, TransformerException, JAXBException { List<String> signatureResourceNames = new LinkedList<String>(); ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(url.openStream(), "UTF8", true, true); ZipArchiveEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if ("_rels/.rels".equals(zipEntry.getName())) { break; } } if (null == zipEntry) { LOG.debug("no _rels/.rels relationship part present"); return signatureResourceNames; } String dsOriginPart = null; JAXBElement<CTRelationships> packageRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller.unmarshal(zipInputStream); CTRelationships packageRelationships = packageRelationshipsElement.getValue(); List<CTRelationship> packageRelationshipList = packageRelationships.getRelationship(); for (CTRelationship packageRelationship : packageRelationshipList) { if (OOXMLSignatureVerifier.DIGITAL_SIGNATURE_ORIGIN_REL_TYPE.equals(packageRelationship.getType())) { dsOriginPart = packageRelationship.getTarget(); break; } } if (null == dsOriginPart) { LOG.debug("no Digital Signature Origin part present"); return signatureResourceNames; } LOG.debug("Digital Signature Origin part: " + dsOriginPart); String dsOriginName = dsOriginPart.substring(dsOriginPart.lastIndexOf("/") + 1); LOG.debug("Digital Signature Origin base: " + dsOriginName); String dsOriginSegment = dsOriginPart.substring(0, dsOriginPart.lastIndexOf("/")) + "/"; LOG.debug("Digital Signature Origin segment: " + dsOriginSegment); String dsOriginRels = dsOriginSegment + "_rels/" + dsOriginName + ".rels"; LOG.debug("Digital Signature Origin relationship part: " + dsOriginRels); if (dsOriginRels.startsWith("/")) { dsOriginRels = dsOriginRels.substring(1); } zipInputStream = new ZipArchiveInputStream(url.openStream(), "UTF8", true, true); while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if (dsOriginRels.equals(zipEntry.getName())) { break; } } if (null == zipEntry) { LOG.debug("no Digital Signature Origin relationship part present"); return signatureResourceNames; } JAXBElement<CTRelationships> dsoRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller.unmarshal(zipInputStream); CTRelationships dsoRelationships = dsoRelationshipsElement.getValue(); List<CTRelationship> dsoRelationshipList = dsoRelationships.getRelationship(); for (CTRelationship dsoRelationship : dsoRelationshipList) { if (OOXMLSignatureVerifier.DIGITAL_SIGNATURE_REL_TYPE.equals(dsoRelationship.getType())) { String signatureResourceName; if (dsoRelationship.getTarget().startsWith("/")) { signatureResourceName = dsoRelationship.getTarget(); } else { signatureResourceName = dsOriginSegment + dsoRelationship.getTarget(); } if (signatureResourceName.startsWith("/")) { signatureResourceName = signatureResourceName.substring(1); } LOG.debug("signature resource name: " + signatureResourceName); signatureResourceNames.add(signatureResourceName); } } return signatureResourceNames; }
00
Code Sample 1: public static byte[] downloadFromUrl(String fileUrl) throws IOException { URL url = new URL(fileUrl); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } return baf.toByteArray(); } Code Sample 2: @NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: private static String sort(final String item) { final char[] chars = item.toCharArray(); for (int i = 1; i < chars.length; i++) { for (int j = 0; j < chars.length - 1; j++) { if (chars[j] > chars[j + 1]) { final char temp = chars[j]; chars[j] = chars[j + 1]; chars[j + 1] = temp; } } } return String.valueOf(chars); }
00
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: private void logoutUser(String session) { try { String data = URLEncoder.encode("SESSION", "UTF-8") + "=" + URLEncoder.encode("" + session, "UTF-8"); if (_log != null) _log.error("Voice: logoutUser = " + m_strUrl + "LogoutUserServlet&" + data); URL url = new URL(m_strUrl + "LogoutUserServlet"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); wr.close(); rd.close(); } catch (Exception e) { if (_log != null) _log.error("Voice error : " + e); } }
11
Code Sample 1: public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
11
Code Sample 1: public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; } Code Sample 2: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; }
00
Code Sample 1: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } } Code Sample 2: public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
00
Code Sample 1: public ValidEPoint[] split(EPoint o, EPoint e1, long v1, EPoint e2) throws MalformedURLException, IOException, NoSuchAlgorithmException, InvalidEPointCertificateException, InvalidKeyException, SignatureException { URLConnection u = new URL(url, "action").openConnection(); OutputStream os; InputStream is; ValidEPoint[] v = new ValidEPoint[2]; u.setDoOutput(true); u.setDoInput(true); u.setAllowUserInteraction(false); os = u.getOutputStream(); os.write(("B=" + URLEncoder.encode(o.toString(), "UTF-8") + "&D=" + Base16.encode(e1.getMD()) + "&F=" + Long.toString(v1) + "&C=" + Base16.encode(e2.getMD())).getBytes()); os.close(); is = u.getInputStream(); v[1] = new ValidEPoint(this, e2, is); is.close(); v[0] = validate(e1); return v; } Code Sample 2: public static void extractZipPackage(String fileName, String destinationFolder) throws Exception { if (NullStatus.isNull(destinationFolder)) { destinationFolder = ""; } new File(destinationFolder).mkdirs(); File inputFile = new File(fileName); ZipFile zipFile = new ZipFile(inputFile); Enumeration<? extends ZipEntry> oEnum = zipFile.entries(); while (oEnum.hasMoreElements()) { ZipEntry zipEntry = oEnum.nextElement(); File file = new File(destinationFolder + "/" + zipEntry.getName()); if (zipEntry.isDirectory()) { file.mkdirs(); } else { String destinationFolderName = destinationFolder + "/" + zipEntry.getName(); destinationFolderName = destinationFolderName.substring(0, destinationFolderName.lastIndexOf("/")); new File(destinationFolderName).mkdirs(); FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(zipFile.getInputStream(zipEntry), fos); fos.close(); } } }
11
Code Sample 1: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) { throw new IOException("FileCopy: no such source file: " + from_file.getPath()); } if (!from_file.isFile()) { throw new IOException("FileCopy: can't copy directory: " + from_file.getPath()); } if (!from_file.canRead()) { throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath()); } if (to_file.isDirectory()) { to_file = new File(to_file, from_file.getName()); } if (to_file.exists()) { if (!to_file.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath()); } int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { throw new IOException("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent(); if (parent == null) { parent = Globals.getDefaultPath(); } 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(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public void anular() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ms = null; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentencia_delete = "DELETE FROM BZOFRENT " + " WHERE REN_OFANY=? AND REN_OFOFI=? AND REN_OFNUM=?"; ms = conn.prepareStatement(sentencia_delete); ms.setInt(1, anoOficio != null ? Integer.parseInt(anoOficio) : 0); ms.setInt(2, oficinaOficio != null ? Integer.parseInt(oficinaOficio) : 0); ms.setInt(3, numeroOficio != null ? Integer.parseInt(numeroOficio) : 0); int afectados = ms.executeUpdate(); if (afectados > 0) { registroActualizado = true; } else { registroActualizado = false; } conn.commit(); } catch (Exception ex) { System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage()); ex.printStackTrace(); registroActualizado = false; errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage()); try { if (conn != null) conn.rollback(); } catch (SQLException sqle) { throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle); } throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex); } finally { ToolsBD.closeConn(conn, ms, null); } } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
00
Code Sample 1: private String getSearchResults(String id) { try { final URL url = new URL("http://www.jaap.nl/api/jaapAPI.do?clientId=iPhone&limit=5&request=details&id=" + id + "&format=JSON&field=street_nr&field=zip&field=city&field=price&field=thumb&field=since&field=houseType&field=area&field=rooms&field=id"); final StringBuilder builder = new StringBuilder(); final BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream())); String s = ""; while ((s = rd.readLine()) != null) { builder.append(s); } rd.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: @Override public synchronized void deleteHardDiskStatistics(String contextName, String path, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHardDiskInvocationsSchemaAndTableName() + " FROM " + this.getHardDiskInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHardDiskElementsSchemaAndTableName() + " ON " + this.getHardDiskElementsSchemaAndTableName() + ".element_id = " + this.getHardDiskInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (path != null) { queryString = queryString + " path LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (path != null) { preparedStatement.setString(indexCounter, path); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting disk statistics.", e); } finally { this.releaseConnection(connection); } }
00
Code Sample 1: private void convertClasses(File source, File destination) throws PostProcessingException, CodeCheckException, IOException { Stack sourceStack = new Stack(); Stack destinationStack = new Stack(); sourceStack.push(source); destinationStack.push(destination); while (!sourceStack.isEmpty()) { source = (File) sourceStack.pop(); destination = (File) destinationStack.pop(); if (!destination.exists()) destination.mkdirs(); File[] files = source.listFiles(); for (int i = 0; i < files.length; i++) { File current = (File) files[i]; if (current.isDirectory()) { sourceStack.push(current); destinationStack.push(new File(destination, current.getName())); } else if (current.getName().endsWith(".class")) { ClassWriter writer = new ClassWriter(); InputStream is = new BufferedInputStream(new FileInputStream(current)); writer.readClass(is); is.close(); if ((getStatusFlags(writer.getClassName(writer.getCurrentClassIndex())) & PP_PROCESSED) != 0) { ClassWriter[] auxWriter = new ClassWriter[1]; transformClass(writer, auxWriter); File output = new File(destination, current.getName()); OutputStream os = new BufferedOutputStream(new FileOutputStream(output)); writer.writeClass(os); os.close(); if (auxWriter[0] != null) { String className = auxWriter[0].getClassName(auxWriter[0].getCurrentClassIndex()); className = className.substring(className.lastIndexOf('.') + 1, className.length()); output = new File(destination, className + ".class"); os = new BufferedOutputStream(new FileOutputStream(output)); auxWriter[0].writeClass(os); os.close(); } } } } } } Code Sample 2: public final int sendMetaData(FileInputStream fis) throws Exception { try { UUID uuid = UUID.randomUUID(); HttpClient client = new SSLHttpClient(); StringBuilder builder = new StringBuilder(mServer).append("?cmd=meta").append("&id=" + uuid); HttpPost method = new HttpPost(builder.toString()); String fileName = uuid + ".metadata"; FileInputStreamPart part = new FileInputStreamPart("data", fileName, fis); MultipartEntity requestContent = new MultipartEntity(new Part[] { part }); method.setEntity(requestContent); HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { return 0; } else { return -1; } } catch (Exception e) { throw new Exception("send meta data", e); } }
00
Code Sample 1: private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); } Code Sample 2: public static String copy(URL url, File dest) throws IOException { if (log.isDebugEnabled()) { log.debug("Fetching: " + url); } IOException error = null; for (int retries = 0; retries < MAX_RETRIES; retries++) { try { OutputStream out = null; InputStream is = null; try { out = new FileOutputStream(dest); if (url.getProtocol().equals("http")) { is = new WebFileInputStream(url); } else { is = url.openStream(); } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); md.update(buf, 0, len); } out.flush(); return bytesToHexString(md.digest()); } catch (ConnectException e) { if (error == null) { error = e; } if (retries < MAX_RETRIES - 1) { log.error(MessageFormat.format("Unable to fetch URL {0}, connection timed out. Will retry...", url.toExternalForm())); try { Thread.sleep(FileHelper.RETRY_SLEEP_TIME); } catch (InterruptedException e2) { } } } catch (SocketTimeoutException e) { if (error == null) { error = e; } if (retries < MAX_RETRIES - 1) { log.error(MessageFormat.format("Unable to fetch URL {0}, timed out. Will retry...", url.toExternalForm())); try { Thread.sleep(FileHelper.RETRY_SLEEP_TIME); } catch (InterruptedException e2) { } } } catch (IOException e) { if (dest.exists()) { try { FileHelper.delete(dest); } catch (IOException e1) { log.error(MessageFormat.format(Messages.getString("FileHelper.UNABLE_DELETE_FILE"), dest), e1); } } throw e; } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(Messages.getString("FileHelper.UNABLE_CLOSE_STREAM"), e); } } if (out != null) { try { out.close(); } catch (IOException e) { log.error(Messages.getString("FileHelper.UNABLE_CLOSE_STREAM"), e); } } } } catch (NoSuchAlgorithmException e) { throw new IOException(MessageFormat.format(Messages.getString("FileHelper.UNABLE_DOWNLOAD_URL"), url), e); } } throw error; }
00
Code Sample 1: protected String updateTwitter() { if (updatingTwitter) return null; updatingTwitter = true; String highestId = null; final Cursor cursor = query(TWITTER_TABLE, new String[] { KEY_TWEET_ID }, null, null, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); highestId = cursor.getString(cursor.getColumnIndex(KEY_TWEET_ID)); } cursor.close(); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("screen_name", TWITTER_ACCOUNT)); nameValuePairs.add(new BasicNameValuePair("count", "" + MAX_TWEETS)); if (highestId != null) nameValuePairs.add(new BasicNameValuePair("since_id", highestId)); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); final HttpClient httpclient = new DefaultHttpClient(mgr, params); final HttpGet request = new HttpGet(); final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); String data = ""; try { final URI uri = new URI(TWITTER_URL + "?" + paramString); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ClientProtocolException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final IOException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } try { final JSONArray tweets = new JSONArray(data); if (tweets == null) { updatingTwitter = false; return "failed"; } if (tweets.length() == 0) { updatingTwitter = false; return "none"; } final SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); final SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH); for (int i = 0; i < tweets.length(); i++) { final JSONObject tweet = tweets.getJSONObject(i); final ContentValues values = new ContentValues(); Log.v(TAG, "Datum van tweet: " + tweet.getString(KEY_TWEET_DATE)); values.put(KEY_TWEET_DATE, formatter.format(parser.parse(tweet.getString(KEY_TWEET_DATE)))); values.put(KEY_TWEET_TEXT, tweet.getString(KEY_TWEET_TEXT)); values.put(KEY_TWEET_ID, tweet.getString(KEY_TWEET_ID)); insert(TWITTER_TABLE, values); } } catch (final JSONException e) { Log.v(TAG, "JSON decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ParseException e) { Log.v(TAG, "Datum decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } purgeTweets(); updatingTwitter = false; return "success"; } Code Sample 2: public static void copyFile(File in, File out) throws FileNotFoundException, IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { sourceChannel.close(); } catch (Exception ex) { } try { destinationChannel.close(); } catch (Exception ex) { } } }
00
Code Sample 1: @Transient private String md5sum(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(text.getBytes()); byte messageDigest[] = md.digest(); return bufferToHex(messageDigest, 0, messageDigest.length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
11
Code Sample 1: @SuppressWarnings("unchecked") public static <T extends Class> Collection<T> listServices(T serviceType, ClassLoader classLoader) throws IOException, ClassNotFoundException { final Collection<T> result = new LinkedHashSet<T>(); final Enumeration<URL> resouces = classLoader.getResources("META-INF/services/" + serviceType.getName()); while (resouces.hasMoreElements()) { final URL url = resouces.nextElement(); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String line = reader.readLine(); while (line != null) { if (line.startsWith("#")) { } else if ("".equals(line.trim())) { } else { final T implClass = (T) Class.forName(line, true, classLoader); if (!serviceType.isAssignableFrom(implClass)) { throw new IllegalStateException(String.format("%s: class %s does not implement required interfafce %s", url, implClass, serviceType)); } result.add(implClass); } line = reader.readLine(); } } finally { reader.close(); } } return result; } Code Sample 2: public static String translate(String s) { try { String result = null; URL url = new URL("http://translate.google.com/translate_t"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("text=" + URLEncoder.encode(s, "UTF-8") + "&langpair="); if (s.matches("[\\u0000-\\u00ff]+")) { out.print("en|ja"); } else { out.print("ja|en"); } out.print("&hl=en&ie=UTF-8&oe=UTF-8"); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("id=result_box"); if (textPos >= 0) { int ltrPos = inputLine.indexOf("dir=ltr", textPos + 9); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 8); if (closePos >= 0) { result = inputLine.substring(ltrPos + 8, closePos); } } } } in.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public void importarHistoricoDeCotacoesDosPapeis(File[] pArquivosTXT, boolean pApagarDadosImportadosAnteriormente, Andamento pAndamento) throws FileNotFoundException, SQLException { if (pApagarDadosImportadosAnteriormente) { Statement stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_COTACAO_AVISTA_LOTE_PDR"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "TRUNCATE TABLE TMP_TB_COTACAO_OUTROS_MERCADOS"; stmtLimpezaInicialDestino.executeUpdate(sql); } final int TAMANHO_DO_REGISTRO = 245; long TAMANHO_DOS_METADADOS_DO_ARQUIVO = 2 * TAMANHO_DO_REGISTRO; long tamanhoDosArquivos = 0; for (File arquivoTXT : pArquivosTXT) { long tamanhoDoArquivo = arquivoTXT.length(); tamanhoDosArquivos += tamanhoDoArquivo; } int quantidadeEstimadaDeRegistros = (int) ((tamanhoDosArquivos - (pArquivosTXT.length * TAMANHO_DOS_METADADOS_DO_ARQUIVO)) / TAMANHO_DO_REGISTRO); String sqlMercadoAVistaLotePadrao = "INSERT INTO TMP_TB_COTACAO_AVISTA_LOTE_PDR(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoMercadoAVistaLotePadrao = (OraclePreparedStatement) conDestino.prepareStatement(sqlMercadoAVistaLotePadrao); stmtDestinoMercadoAVistaLotePadrao.setExecuteBatch(COMANDOS_POR_LOTE); String sqlOutrosMercados = "INSERT INTO TMP_TB_COTACAO_OUTROS_MERCADOS(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoOutrosMercados = (OraclePreparedStatement) conDestino.prepareStatement(sqlOutrosMercados); stmtDestinoOutrosMercados.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportadosDosArquivos = 0; Scanner in = null; int numeroDoRegistro = -1; try { for (File arquivoTXT : pArquivosTXT) { int quantidadeDeRegistrosImportadosDoArquivoAtual = 0; int vDATA_PREGAO; try { in = new Scanner(new FileInputStream(arquivoTXT), Constantes.CONJUNTO_DE_CARACTERES_DOS_ARQUIVOS_TEXTO_DA_BOVESPA.name()); String registro; numeroDoRegistro = 0; while (in.hasNextLine()) { ++numeroDoRegistro; registro = in.nextLine(); if (registro.length() != TAMANHO_DO_REGISTRO) throw new ProblemaNaImportacaoDeArquivo(); if (registro.startsWith("01")) { stmtDestinoMercadoAVistaLotePadrao.clearParameters(); stmtDestinoOutrosMercados.clearParameters(); vDATA_PREGAO = Integer.parseInt(registro.substring(2, 10).trim()); int vCODBDI = Integer.parseInt(registro.substring(10, 12).trim()); String vCODNEG = registro.substring(12, 24).trim(); int vTPMERC = Integer.parseInt(registro.substring(24, 27).trim()); String vNOMRES = registro.substring(27, 39).trim(); String vESPECI = registro.substring(39, 49).trim(); String vPRAZOT = registro.substring(49, 52).trim(); String vMODREF = registro.substring(52, 56).trim(); BigDecimal vPREABE = obterBigDecimal(registro.substring(56, 69).trim(), 13, 2); BigDecimal vPREMAX = obterBigDecimal(registro.substring(69, 82).trim(), 13, 2); BigDecimal vPREMIN = obterBigDecimal(registro.substring(82, 95).trim(), 13, 2); BigDecimal vPREMED = obterBigDecimal(registro.substring(95, 108).trim(), 13, 2); BigDecimal vPREULT = obterBigDecimal(registro.substring(108, 121).trim(), 13, 2); BigDecimal vPREOFC = obterBigDecimal(registro.substring(121, 134).trim(), 13, 2); BigDecimal vPREOFV = obterBigDecimal(registro.substring(134, 147).trim(), 13, 2); int vTOTNEG = Integer.parseInt(registro.substring(147, 152).trim()); BigDecimal vQUATOT = new BigDecimal(registro.substring(152, 170).trim()); BigDecimal vVOLTOT = obterBigDecimal(registro.substring(170, 188).trim(), 18, 2); BigDecimal vPREEXE = obterBigDecimal(registro.substring(188, 201).trim(), 13, 2); int vINDOPC = Integer.parseInt(registro.substring(201, 202).trim()); int vDATVEN = Integer.parseInt(registro.substring(202, 210).trim()); int vFATCOT = Integer.parseInt(registro.substring(210, 217).trim()); BigDecimal vPTOEXE = obterBigDecimal(registro.substring(217, 230).trim(), 13, 6); String vCODISI = registro.substring(230, 242).trim(); int vDISMES = Integer.parseInt(registro.substring(242, 245).trim()); boolean mercadoAVistaLotePadrao = (vTPMERC == 10 && vCODBDI == 2); OraclePreparedStatement stmtDestino; if (mercadoAVistaLotePadrao) { stmtDestino = stmtDestinoMercadoAVistaLotePadrao; } else { stmtDestino = stmtDestinoOutrosMercados; } stmtDestino.setIntAtName("DATA_PREGAO", vDATA_PREGAO); stmtDestino.setIntAtName("CODBDI", vCODBDI); stmtDestino.setStringAtName("CODNEG", vCODNEG); stmtDestino.setIntAtName("TPMERC", vTPMERC); stmtDestino.setStringAtName("NOMRES", vNOMRES); stmtDestino.setStringAtName("ESPECI", vESPECI); stmtDestino.setStringAtName("PRAZOT", vPRAZOT); stmtDestino.setStringAtName("MODREF", vMODREF); stmtDestino.setBigDecimalAtName("PREABE", vPREABE); stmtDestino.setBigDecimalAtName("PREMAX", vPREMAX); stmtDestino.setBigDecimalAtName("PREMIN", vPREMIN); stmtDestino.setBigDecimalAtName("PREMED", vPREMED); stmtDestino.setBigDecimalAtName("PREULT", vPREULT); stmtDestino.setBigDecimalAtName("PREOFC", vPREOFC); stmtDestino.setBigDecimalAtName("PREOFV", vPREOFV); stmtDestino.setIntAtName("TOTNEG", vTOTNEG); stmtDestino.setBigDecimalAtName("QUATOT", vQUATOT); stmtDestino.setBigDecimalAtName("VOLTOT", vVOLTOT); stmtDestino.setBigDecimalAtName("PREEXE", vPREEXE); stmtDestino.setIntAtName("INDOPC", vINDOPC); stmtDestino.setIntAtName("DATVEN", vDATVEN); stmtDestino.setIntAtName("FATCOT", vFATCOT); stmtDestino.setBigDecimalAtName("PTOEXE", vPTOEXE); stmtDestino.setStringAtName("CODISI", vCODISI); stmtDestino.setIntAtName("DISMES", vDISMES); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportadosDoArquivoAtual++; quantidadeDeRegistrosImportadosDosArquivos++; } else if (registro.startsWith("99")) { BigDecimal totalDeRegistros = obterBigDecimal(registro.substring(31, 42).trim(), 11, 0); assert (totalDeRegistros.intValue() - 2) == quantidadeDeRegistrosImportadosDoArquivoAtual : "Quantidade de registros divergente"; break; } double percentualCompleto = (double) quantidadeDeRegistrosImportadosDosArquivos / quantidadeEstimadaDeRegistros * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = arquivoTXT.getName(); problemaDetalhado.linhaProblematicaDoArquivo = numeroDoRegistro; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { in.close(); } } } finally { pAndamento.setPercentualCompleto(100); stmtDestinoMercadoAVistaLotePadrao.close(); stmtDestinoOutrosMercados.close(); } } Code Sample 2: public ProgramMessageSymbol deleteProgramMessageSymbol(int id) throws AdaptationException { ProgramMessageSymbol pmt = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramMessageSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { String msg = "Attempt to delete program message type " + "failed."; log.error(msg); ; throw new AdaptationException(msg); } pmt = getProgramMessageSymbol(resultSet); query = "DELETE FROM ProgramMessageSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramMessageSymbol"; 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 pmt; }
11
Code Sample 1: private String generateCode(String seed) { try { Security.addProvider(new FNVProvider()); MessageDigest digest = MessageDigest.getInstance("FNV-1a"); digest.update((seed + UUID.randomUUID().toString()).getBytes()); byte[] hash1 = digest.digest(); String sHash1 = "m" + (new String(LibraryBase64.encode(hash1))).replaceAll("=", "").replaceAll("-", "_"); return sHash1; } catch (Exception e) { e.printStackTrace(); } return ""; } Code Sample 2: public static String generateMessageId(String plain) { byte[] cipher = new byte[35]; String messageId = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes()); cipher = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < cipher.length; i++) { String hex = Integer.toHexString(0xff & cipher[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } StringBuffer pass = new StringBuffer(); pass.append(sb.substring(0, 6)); pass.append("H"); pass.append(sb.substring(6, 11)); pass.append("H"); pass.append(sb.substring(11, 21)); pass.append("H"); pass.append(sb.substring(21)); messageId = new String(pass); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return messageId; }
11
Code Sample 1: public static void appendFile(String namePrefix, File baseDir, File file, ZipOutputStream zipOut) throws IOException { Assert.Arg.notNull(baseDir, "baseDir"); Assert.Arg.notNull(file, "file"); Assert.Arg.notNull(zipOut, "zipOut"); if (namePrefix == null) namePrefix = ""; String path = FileSystemUtils.getRelativePath(baseDir, file); ZipEntry zipEntry = new ZipEntry(namePrefix + path); zipOut.putNextEntry(zipEntry); InputStream fileInput = FileUtils.openInputStream(file); try { org.apache.commons.io.IOUtils.copyLarge(fileInput, zipOut); } finally { fileInput.close(); } } Code Sample 2: public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: public static void main(String[] args) { Option optHelp = new Option("h", "help", false, "print this message"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", true, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(-1); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } for (String tmpFilePath : tmpArgs) { System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(-1); } continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); System.exit(-1); } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (failFast && SignatureVerification.isError(tmpResult.getVerificationResultCode())) { System.exit(tmpResult.getVerificationResultCode()); } } } } } Code Sample 2: public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); }
00
Code Sample 1: protected synchronized InputStream openURLConnection(StreamDataSetDescriptor dsd, Datum start, Datum end, StringBuffer additionalFormData) throws DasException { String[] tokens = dsd.getDataSetID().split("\\?|\\&"); String dataSetID = tokens[1]; try { String formData = createFormDataString(dataSetID, start, end, additionalFormData); if (dsd.isRestrictedAccess()) { key = server.getKey(""); if (key != null) { formData += "&key=" + URLEncoder.encode(key.toString(), "UTF-8"); } } if (redirect) { formData += "&redirect=1"; } URL serverURL = this.server.getURL(formData); this.lastRequestURL = String.valueOf(serverURL); DasLogger.getLogger(DasLogger.DATA_TRANSFER_LOG).info("opening " + serverURL.toString()); URLConnection urlConnection = serverURL.openConnection(); urlConnection.connect(); String contentType = urlConnection.getContentType(); if (!contentType.equalsIgnoreCase("application/octet-stream")) { BufferedReader bin = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line = bin.readLine(); String message = ""; while (line != null) { message = message.concat(line); line = bin.readLine(); } throw new DasIOException(message); } InputStream in = urlConnection.getInputStream(); if (isLegacyStream()) { return processLegacyStream(in); } else { throw new UnsupportedOperationException(); } } catch (IOException e) { throw new DasIOException(e); } } Code Sample 2: private static InputStream download(String url) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse httpresponse = httpclient.execute(httpget); HttpEntity httpentity = httpresponse.getEntity(); if (httpentity != null) { return httpentity.getContent(); } } catch (Exception e) { Log.e("Android", e.getMessage()); } return null; }
11
Code Sample 1: public ScoreModel(URL url) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; list = new ArrayList<ScoreModelItem>(); map = new HashMap<String, ScoreModelItem>(); line = in.readLine(); int n = 1; String[] rowAttrib; ScoreModelItem item; while ((line = in.readLine()) != null) { rowAttrib = line.split(";"); item = new ScoreModelItem(n, Double.valueOf(rowAttrib[3]), Double.valueOf(rowAttrib[4]), Double.valueOf(rowAttrib[2]), Double.valueOf(rowAttrib[5]), rowAttrib[1]); list.add(item); map.put(item.getHash(), item); n++; } in.close(); } Code Sample 2: protected Configuration() { try { Enumeration<URL> resources = getClass().getClassLoader().getResources("activejdbc_models.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); LogFilter.log(logger, "Load models from: " + url.toExternalForm()); InputStream inputStream = null; try { inputStream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { String[] parts = Util.split(line, ':'); String modelName = parts[0]; String dbName = parts[1]; if (modelsMap.get(dbName) == null) { modelsMap.put(dbName, new ArrayList<String>()); } modelsMap.get(dbName).add(modelName); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) inputStream.close(); } } } catch (IOException e) { throw new InitException(e); } if (modelsMap.isEmpty()) { LogFilter.log(logger, "ActiveJDBC Warning: Cannot locate any models, assuming project without models."); return; } try { InputStream in = getClass().getResourceAsStream("/activejdbc.properties"); if (in != null) properties.load(in); } catch (Exception e) { throw new InitException(e); } String cacheManagerClass = properties.getProperty("cache.manager"); if (cacheManagerClass != null) { try { Class cmc = Class.forName(cacheManagerClass); cacheManager = (CacheManager) cmc.newInstance(); } catch (Exception e) { throw new InitException("failed to initialize a CacheManager. Please, ensure that the property " + "'cache.manager' points to correct class which extends 'activejdbc.cache.CacheManager' class and provides a default constructor.", e); } } }
00
Code Sample 1: private static void setEnvEntry(File fromEAR, File toEAR, String ejbJarName, String envEntryName, String envEntryValue) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEAR)); FileOutputStream fos = new FileOutputStream(toEAR); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals(ejbJarName)) { content = editEJBJAR(next, content, envEntryName, envEntryValue); next = new ZipEntry(ejbJarName); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } 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: public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); } Code Sample 2: public static URL getWikipediaPage(String concept, String language) throws MalformedURLException, IOException { String url = "http://" + language + ".wikipedia.org/wiki/Special:Search?search=" + URLEncoder.encode(concept, UTF_8_ENCODING) + "&go=Go"; HttpURLConnection.setFollowRedirects(false); HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.connect(); int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return null; } else if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM) { return new URL(httpConnection.getHeaderField("Location")); } else { logger.warn("Unexpected response code (" + responseCode + ")."); return null; } } finally { if (httpConnection != null) { httpConnection.disconnect(); } } }
11
Code Sample 1: @Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { LogUtil.d(TAG, "Copying file %s to %s", src, dst); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dst).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { closeSafe(inChannel); closeSafe(outChannel); } }
00
Code Sample 1: public void moveNext(String[] showOrder, String[] orgID, String targetShowOrder, String targetOrgID) throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; int moveCount = showOrder.length; DBOperation dbo = factory.createDBOperation(POOL_NAME); String strQuery = "select show_order from " + Common.ORGANIZE_TABLE + " where show_order=" + showOrder[0] + " and organize_id= '" + orgID[0] + "'"; try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strQuery); result = ps.executeQuery(); int minOrderNo = 0; if (result.next()) { minOrderNo = result.getInt(1); } String[] sqls = new String[moveCount + 1]; sqls[0] = "update " + Common.ORGANIZE_TABLE + " set show_order=" + minOrderNo + " where show_order=" + targetShowOrder + " and organize_id= '" + targetOrgID + "'"; for (int i = 0; i < showOrder.length; i++) { sqls[i + 1] = "update " + Common.ORGANIZE_TABLE + " set show_order=show_order+1" + " where show_order=" + showOrder[i] + " and organize_id= '" + orgID[i] + "'"; } for (int j = 0; j < sqls.length; j++) { ps = con.prepareStatement(sqls[j]); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new CesSystemException("Organize.moveNext(): ERROR Inserting data " + "in T_SYS_ORGANIZE update !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { if (con != null) { con.rollback(); } throw new CesSystemException("Organize.moveNext(): SQLException while mov organize order " + " :\n\t" + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } Code Sample 2: public String load(URL url) throws LoaderException { log.debug("loading content"); log.trace("opening connection: " + url); BufferedReader in = null; URLConnection conn = null; try { conn = url.openConnection(); in = null; if (encodedProxyLogin != null) { conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedProxyLogin); } } catch (IOException ioe) { log.warn("Error create connection"); throw new LoaderException("Error create connection", ioe); } log.trace("connection opened, reading ... "); StringBuilder buffer = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } } catch (IOException ioe) { log.warn("Error loading content"); throw new LoaderException("Error reading content. ", ioe); } finally { try { in.close(); } catch (Exception e) { } } log.debug("content loaded"); return buffer.toString(); }
00
Code Sample 1: String fetch_pls(String pls) { InputStream pstream = null; if (pls.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), pls); else url = new URL(pls); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + pls); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; if (line.startsWith("File1=")) { byte[] foo = line.getBytes(); int i = 6; for (; i < foo.length; i++) { if (foo[i] == 0x0d) break; } return line.substring(6, i); } } return null; } Code Sample 2: @SuppressWarnings("unused") private GraphicalViewer createGraphicalViewer(Composite parent) { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getContent()); return viewer; }
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 void connect(String username, String passwordMd5) { this.username = username; this.passwordMd5 = passwordMd5; StringBuffer handshakeUrl = new StringBuffer(); handshakeUrl.append("http://ws.audioscrobbler.com/radio/handshake.php?version="); handshakeUrl.append(LastFM.VERSION); handshakeUrl.append("&platform=linux&username="); handshakeUrl.append(this.username); handshakeUrl.append("&passwordmd5="); handshakeUrl.append(this.passwordMd5); handshakeUrl.append("&language=en&player=aTunes"); URL url; try { url = new URL(handshakeUrl.toString()); URLConnection connection = url.openConnection(); InputStream inputStream = new BufferedInputStream(connection.getInputStream()); byte[] buffer = new byte[4069]; int read = 0; StringBuffer result = new StringBuffer(); while ((read = inputStream.read(buffer)) > -1) { result.append((new String(buffer, 0, read))); } String[] rows = result.toString().split("\n"); this.data = new HashMap<String, String>(); for (String row : rows) { row = row.trim(); int firstEquals = row.indexOf("="); data.put(row.substring(0, firstEquals), row.substring(firstEquals + 1)); } String streamingUrl = data.get("stream_url"); streamingUrl = streamingUrl.substring(7); int delimiter = streamingUrl.indexOf("/"); String hostname = streamingUrl.substring(0, delimiter); String path = streamingUrl.substring(delimiter + 1); String[] tokens = hostname.split(":"); hostname = tokens[0]; int port = Integer.parseInt(tokens[1]); this.lastFmSocket = new Socket(hostname, port); OutputStreamWriter osw = new OutputStreamWriter(this.lastFmSocket.getOutputStream()); osw.write("GET /" + path + " HTTP/1.0\r\n"); osw.write("Host: " + hostname + "\r\n"); osw.write("\r\n"); osw.flush(); this.lastFmInputStream = this.lastFmSocket.getInputStream(); result = new StringBuffer(); while ((read = this.lastFmInputStream.read(buffer)) > -1) { String line = new String(buffer, 0, read); result.append(line); if (line.contains("\r\n\r\n")) break; } String response = result.toString(); logger.info("Result: " + response); if (!response.startsWith("HTTP/1.0 200 OK")) { this.lastFmSocket.close(); throw new LastFmException("Could not handshake with lastfm. Check credential!"); } StringBuffer sb = new StringBuffer(); sb.append("http://"); sb.append(this.data.get("base_url")); sb.append(this.data.get("base_path")); sb.append("/xspf.php?sk="); sb.append(this.data.get("session")); sb.append("&discovery=1&desktop="); sb.append(LastFM.VERSION); logger.info(sb.toString()); this.playlistUrl = new URL(sb.toString()); this.playlist = this.playlistParser.fetchPlaylist(this.playlistUrl.toString()); Iterator<LastFmTrack> it = this.playlist.iterator(); while (it.hasNext()) { System.out.println(it.next().getCreator()); } this.connected = true; } catch (MalformedURLException e) { throw new LastFmException("Could not handshake with lastfm", e.getCause()); } catch (IOException e) { throw new LastFmException("Could not initialise lastfm", e.getCause()); } }
11
Code Sample 1: public void testCodingCompletedFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 5); encoder.write(wrap("stuff")); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("more stuff"); wrtout.flush(); wrtout.close(); try { FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 10); fail("IllegalStateException should have been thrown"); } catch (IllegalStateException ex) { } finally { tmpFile.delete(); } } Code Sample 2: public static void copy(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { InputStream input = (InputStream) ((NativeJavaObject) args[0]).unwrap(); OutputStream output = (OutputStream) ((NativeJavaObject) args[1]).unwrap(); IOUtils.copy(input, output); }
11
Code Sample 1: public static String md5Hash(String inString) throws TopicSpacesException { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(inString.getBytes()); byte[] array = md5.digest(); StringBuffer buf = new StringBuffer(); int len = array.length; for (int i = 0; i < len; i++) { int b = array[i] & 0xFF; buf.append(Integer.toHexString(b)); } return buf.toString(); } catch (Exception x) { throw new TopicSpacesException(x); } } Code Sample 2: public static String makeMD5(String input) throws Exception { String dstr = null; byte[] digest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); digest = md.digest(); dstr = new BigInteger(1, digest).toString(16); if (dstr.length() % 2 > 0) { dstr = "0" + dstr; } } catch (Exception e) { throw new Exception("Erro inesperado em makeMD5(): " + e.toString(), e); } return dstr; }
11
Code Sample 1: protected static String getBiopaxId(Reaction reaction) { String id = null; if (reaction.getId() > Reaction.NO_ID_ASSIGNED) { id = reaction.getId().toString(); } else { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(reaction.getTextualRepresentation().getBytes()); byte[] digestBytes = md.digest(); StringBuilder digesterSb = new StringBuilder(32); for (int i = 0; i < digestBytes.length; i++) { int intValue = digestBytes[i] & 0xFF; if (intValue < 0x10) digesterSb.append('0'); digesterSb.append(Integer.toHexString(intValue)); } id = digesterSb.toString(); } catch (NoSuchAlgorithmException e) { } } return id; } Code Sample 2: public static String generateHash(String value) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(value.getBytes()); } catch (NoSuchAlgorithmException e) { log.error("Could not find the requested hash method: " + e.getMessage()); } byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); }
00
Code Sample 1: private void moveFile(File orig, File target) throws IOException { byte buffer[] = new byte[1000]; int bread = 0; FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(target); while (bread != -1) { bread = fis.read(buffer); if (bread != -1) fos.write(buffer, 0, bread); } fis.close(); fos.close(); orig.delete(); } Code Sample 2: String fetch_m3u(String m3u) { InputStream pstream = null; if (m3u.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; return line; } return null; }
11
Code Sample 1: public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwd = null; SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); pwd = new byte[digest.length + SALT_LENGTH]; System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); return byteToHexString(pwd); } Code Sample 2: public static String encryptPass2(String pass) throws UnsupportedEncodingException { String passEncrypt; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } md5.update(pass.getBytes()); String dis = new String(md5.digest(), 10); passEncrypt = dis.toString(); return passEncrypt; }
00
Code Sample 1: public static void main(String args[]) { if (args.length < 1) { printUsage(); } URL url; BufferedReader in = null; try { url = new URL(args[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if (responseCode == 200) { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } else { System.out.println("Response code " + responseCode + " means there was an error reading url " + args[0]); } } catch (IOException e) { System.err.println("IOException attempting to read url " + args[0]); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception ignore) { } } } } Code Sample 2: public static void copy(String from, String to) throws Exception { File inputFile = new File(from); File outputFile = new File(to); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); }
00
Code Sample 1: public static void main(String[] args) throws IOException { String urltext = "http://www.vogella.de"; URL url = new URL(urltext); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } Code Sample 2: public void constructFundamentalView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { FundView = new BufferedWriter(new FileWriter("InfoFiles/FundamentalView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; FundView.write(className); FundView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; FundView.write("StartOfMethod"); FundView.newLine(); FundView.write(methodName); FundView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(readArray[i + j]); FundView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(writeArray[i + j]); FundView.newLine(); } } } } } FundView.write("EndOfMethod"); FundView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { FundView.write("EndOfClass"); FundView.newLine(); classWritten = false; } } PC.close(); FundView.close(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: @Test public void testFromFile() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor_float.net"), new FileOutputStream(temp)); Fann fann = new Fann(temp.getPath()); assertEquals(2, fann.getNumInputNeurons()); assertEquals(1, fann.getNumOutputNeurons()); assertEquals(-1f, fann.run(new float[] { -1, -1 })[0], .2f); assertEquals(1f, fann.run(new float[] { -1, 1 })[0], .2f); assertEquals(1f, fann.run(new float[] { 1, -1 })[0], .2f); assertEquals(-1f, fann.run(new float[] { 1, 1 })[0], .2f); fann.close(); } Code Sample 2: public 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(); }
11
Code Sample 1: public boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } } Code Sample 2: public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { ReadableByteChannel in = Channels.newChannel((new FileInputStream("/home/sannies/suckerpunch-distantplanet_h1080p/suckerpunch-distantplanet_h1080p.mov"))); Movie movie = MovieCreator.build(in); in.close(); List<Track> tracks = movie.getTracks(); movie.setTracks(new LinkedList<Track>()); double startTime = 35.000; double endTime = 145.000; boolean timeCorrected = false; for (Track track : tracks) { if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) { if (timeCorrected) { throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported."); } startTime = correctTimeToNextSyncSample(track, startTime); endTime = correctTimeToNextSyncSample(track, endTime); timeCorrected = true; } } for (Track track : tracks) { long currentSample = 0; double currentTime = 0; long startSample = -1; long endSample = -1; for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) { TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i); for (int j = 0; j < entry.getCount(); j++) { if (currentTime <= startTime) { startSample = currentSample; } if (currentTime <= endTime) { endSample = currentSample; } else { break; } currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale(); currentSample++; } } movie.addTrack(new CroppedTrack(track, startSample, endSample)); } long start1 = System.currentTimeMillis(); IsoFile out = new DefaultMp4Builder().build(movie); long start2 = System.currentTimeMillis(); FileOutputStream fos = new FileOutputStream(String.format("output-%f-%f.mp4", startTime, endTime)); FileChannel fc = fos.getChannel(); out.getBox(fc); fc.close(); fos.close(); long start3 = System.currentTimeMillis(); System.err.println("Building IsoFile took : " + (start2 - start1) + "ms"); System.err.println("Writing IsoFile took : " + (start3 - start2) + "ms"); System.err.println("Writing IsoFile speed : " + (new File(String.format("output-%f-%f.mp4", startTime, endTime)).length() / (start3 - start2) / 1000) + "MB/s"); } Code Sample 2: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
11
Code Sample 1: private String computeHash(String str) { StringBuffer hexBuffer = new StringBuffer(); byte[] bytes; int i; try { MessageDigest hashAlgorithm = MessageDigest.getInstance(hashAlgorithmName); hashAlgorithm.reset(); hashAlgorithm.update(str.getBytes()); bytes = hashAlgorithm.digest(); } catch (NoSuchAlgorithmException e) { return null; } for (i = 0; i < bytes.length; i++) hexBuffer.append(((bytes[i] >= 0 && bytes[i] <= 15) ? "0" : "") + Integer.toHexString(bytes[i] & 0xFF)); return hexBuffer.toString(); } Code Sample 2: public static String hashPassword(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { logger.log(Level.SEVERE, "Problem hashing password.", e); } return new String(Base64.encodeBase64(md.digest())); }
11
Code Sample 1: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void end() throws Exception { handle.waitFor(); Calendar endTime = Calendar.getInstance(); File resultsDir = new File(runDir, "results"); if (!resultsDir.isDirectory()) throw new Exception("The results directory not found!"); String resHtml = null; String resTxt = null; String[] resultFiles = resultsDir.list(); for (String resultFile : resultFiles) { if (resultFile.indexOf("html") >= 0) resHtml = resultFile; else if (resultFile.indexOf("txt") >= 0) resTxt = resultFile; } if (resHtml == null) throw new IOException("SPECweb2005 output (html) file not found"); if (resTxt == null) throw new IOException("SPECweb2005 output (txt) file not found"); File resultHtml = new File(resultsDir, resHtml); copyFile(resultHtml.getAbsolutePath(), runDir + "SPECWeb-result.html", false); BufferedReader reader = new BufferedReader(new FileReader(new File(resultsDir, resTxt))); logger.fine("Text file: " + resultsDir + resTxt); Writer writer = new FileWriter(runDir + "summary.xml"); SummaryParser parser = new SummaryParser(getRunId(), startTime, endTime, logger); parser.convert(reader, writer); writer.close(); reader.close(); }
00
Code Sample 1: private static Image tryLoadImageFromFile(String filename, String path, int width, int height) { Image image = null; try { URL url; url = new URL("file:" + path + pathSeparator + fixFilename(filename)); if (url.openStream() != null) { image = Toolkit.getDefaultToolkit().getImage(url); } } catch (MalformedURLException e) { } catch (IOException e) { } if (image != null) { return image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH); } else { return null; } } Code Sample 2: @Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); }
00
Code Sample 1: private boolean goToForum() { URL url = null; URLConnection urlConn = null; int code = 0; boolean gotNumReplies = false; boolean gotMsgNum = false; try { url = new URL("http://" + m_host + "/forums/index.php?topic=" + m_gameId + ".new"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(false); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); m_referer = url.toString(); readCookies(urlConn); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code != 200) { String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = ""; Pattern p_numReplies = Pattern.compile(".*?;num_replies=(\\d+)\".*"); Pattern p_msgNum = Pattern.compile(".*?<a name=\"msg(\\d+)\"></a><a name=\"new\"></a>.*"); Pattern p_attachId = Pattern.compile(".*?action=dlattach;topic=" + m_gameId + ".0;attach=(\\d+)\">.*"); while ((line = in.readLine()) != null) { if (!gotNumReplies) { Matcher match_numReplies = p_numReplies.matcher(line); if (match_numReplies.matches()) { m_numReplies = match_numReplies.group(1); gotNumReplies = true; continue; } } if (!gotMsgNum) { Matcher match_msgNum = p_msgNum.matcher(line); if (match_msgNum.matches()) { m_msgNum = match_msgNum.group(1); gotMsgNum = true; continue; } } Matcher match_attachId = p_attachId.matcher(line); if (match_attachId.matches()) m_attachId = match_attachId.group(1); } in.close(); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotNumReplies || !gotMsgNum) { m_turnSummaryRef = "Error: "; if (!gotNumReplies) m_turnSummaryRef += "No num_replies found in A&A.org forum topic. "; if (!gotMsgNum) m_turnSummaryRef += "No msgXXXXXX found in A&A.org forum topic. "; return false; } return true; } Code Sample 2: private void processStylesheetFile() { InputStream in = null; OutputStream out = null; try { String filename; if (line.hasOption("stylesheetfile")) { filename = line.getOptionValue("stylesheetfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); } else { ClassLoader cl = this.getClass().getClassLoader(); filename = "stylesheet.css"; in = cl.getResourceAsStream(RESOURCE_PKG + "/stylesheet.css"); } baseProperties.setProperty("stylesheetfilename", filename); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } }
00
Code Sample 1: private ArrayList<String> getFiles(String date) { ArrayList<String> files = new ArrayList<String>(); String info = ""; try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS + date + "/"); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf(".bz2"); if (pos != -1) { token = token.substring(1, pos + 4); files.add(token); } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return files; } Code Sample 2: 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(); } } }
00
Code Sample 1: @Override public JSONObject runCommand(JSONObject payload, HttpSession session) throws DefinedException { String sessionId = session.getId(); log.debug("Login -> runCommand SID: " + sessionId); JSONObject toReturn = new JSONObject(); boolean isOK = true; String username = null; try { username = payload.getString(ComConstants.LogIn.Request.USERNAME); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing username parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } String password = null; if (isOK) { try { password = payload.getString(ComConstants.LogIn.Request.PASSWORD); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing password parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } } if (isOK) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("SessionId=" + sessionId + ", MD5 algorithm does not exist", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } m.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, m.digest()).toString(16); UserSession userSession = pli.login(username, password); try { if (userSession != null) { session.setAttribute("user", userSession); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_OK.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_OK.getStatusMessage()); } else { log.error("SessionId=" + sessionId + ", Login failed: username=" + username + " not found"); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusMessage()); } } catch (JSONException e) { log.error("SessionId=" + sessionId + ", JSON exception occured in response", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } } log.debug("Login <- runCommand SID: " + sessionId); return toReturn; } Code Sample 2: protected InputStream callApiMethod(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createBingSearchApiClientException(error); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingSearchException(e); } }
00
Code Sample 1: public GEItem lookup(final int itemID) { try { URL url = new URL(GrandExchange.HOST + GrandExchange.GET + itemID); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; boolean exists = false; int i = 0; double[] values = new double[4]; String name = "", examine = ""; while ((input = br.readLine()) != null) { if (input.contains("<div class=\"brown_box main_ge_page") && !exists) { if (!input.contains("vertically_spaced")) { return null; } exists = true; br.readLine(); br.readLine(); name = br.readLine(); } else if (input.contains("<img id=\"item_image\" src=\"")) { examine = br.readLine(); } else if (input.matches("(?i).+ (price|days):</b> .+")) { values[i] = parse(input); i++; } else if (input.matches("<div id=\"legend\">")) break; } return new GEItem(name, examine, itemID, values); } catch (IOException ignore) { } return null; } Code Sample 2: @Test public void test01_ok_failed_500() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(chartURL); HttpResponse response = client.execute(post); assertEquals("failed code for ", 500, response.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } }
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 doConvert(HttpServletResponse response, ConversionRequestResolver rr, EGE ege, ConversionsPath cpath) throws FileUploadException, IOException, RequestResolvingException, EGEException, FileNotFoundException, ConverterException, ZipException { InputStream is = null; OutputStream os = null; if (ServletFileUpload.isMultipartContent(rr.getRequest())) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(rr.getRequest()); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { is = item.openStream(); applyConversionsProperties(rr.getConversionProperties(), cpath); DataBuffer buffer = new DataBuffer(0, EGEConstants.BUFFER_TEMP_PATH); String alloc = buffer.allocate(is); InputStream ins = buffer.getDataAsStream(alloc); is.close(); try { ValidationResult vRes = ege.performValidation(ins, cpath.getInputDataType()); if (vRes.getStatus().equals(ValidationResult.Status.FATAL)) { ValidationServlet valServ = new ValidationServlet(); valServ.printValidationResult(response, vRes); try { ins.close(); } finally { buffer.removeData(alloc, true); } return; } } catch (ValidatorException vex) { LOGGER.warn(vex.getMessage()); } finally { try { ins.close(); } catch (Exception ex) { } } File zipFile = null; FileOutputStream fos = null; String newTemp = UUID.randomUUID().toString(); IOResolver ior = EGEConfigurationManager.getInstance().getStandardIOResolver(); File buffDir = new File(buffer.getDataDir(alloc)); zipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + EZP_EXT); fos = new FileOutputStream(zipFile); ior.compressData(buffDir, fos); ins = new FileInputStream(zipFile); File szipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + ZIP_EXT); fos = new FileOutputStream(szipFile); try { try { ege.performConversion(ins, fos, cpath); } finally { fos.close(); } boolean isComplex = EGEIOUtils.isComplexZip(szipFile); response.setContentType(APPLICATION_OCTET_STREAM); String fN = item.getName().substring(0, item.getName().lastIndexOf(".")); if (isComplex) { String fileExt; if (cpath.getOutputDataType().getMimeType().equals(APPLICATION_MSWORD)) { fileExt = DOCX_EXT; } else { fileExt = ZIP_EXT; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); FileInputStream fis = new FileInputStream(szipFile); os = response.getOutputStream(); try { EGEIOUtils.copyStream(fis, os); } finally { fis.close(); } } else { String fileExt = getMimeExtensionProvider().getFileExtension(cpath.getOutputDataType().getMimeType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); os = response.getOutputStream(); EGEIOUtils.unzipSingleFile(new ZipFile(szipFile), os); } } finally { ins.close(); if (os != null) { os.flush(); os.close(); } buffer.clear(true); szipFile.delete(); if (zipFile != null) { zipFile.delete(); } } } } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } }
00
Code Sample 1: public void update() { try { String passwordMD5 = new String(); if (this.password != null && this.password.length() > 0) { MessageDigest md = MessageDigest.getInstance("md5"); md.update(this.password.getBytes()); byte[] digest = md.digest(); for (int i = 0; i < digest.length; i++) { passwordMD5 += Integer.toHexString((digest[i] >> 4) & 0xf); passwordMD5 += Integer.toHexString((digest[i] & 0xf)); } } this.authCode = new String(Base64Encoder.encode(new String(this.username + ";" + passwordMD5).getBytes())); } catch (Throwable throwable) { throwable.printStackTrace(); } } Code Sample 2: @TestTargets({ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies that the ObjectInputStream constructor calls checkPermission on security manager.", method = "ObjectInputStream", args = { InputStream.class }) }) public void test_ObjectInputStream2() throws IOException { class TestSecurityManager extends SecurityManager { boolean called; Permission permission; void reset() { called = false; permission = null; } @Override public void checkPermission(Permission permission) { if (permission instanceof SerializablePermission) { called = true; this.permission = permission; } } } class TestObjectInputStream extends ObjectInputStream { TestObjectInputStream(InputStream s) throws StreamCorruptedException, IOException { super(s); } } class TestObjectInputStream_readFields extends ObjectInputStream { TestObjectInputStream_readFields(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public GetField readFields() throws IOException, ClassNotFoundException, NotActiveException { return super.readFields(); } } class TestObjectInputStream_readUnshared extends ObjectInputStream { TestObjectInputStream_readUnshared(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public Object readUnshared() throws IOException, ClassNotFoundException { return super.readUnshared(); } } long id = new java.util.Date().getTime(); String filename = "SecurityPermissionsTest_" + id; File f = File.createTempFile(filename, null); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(new Node()); oos.flush(); oos.close(); f.deleteOnExit(); TestSecurityManager s = new TestSecurityManager(); System.setSecurityManager(s); s.reset(); new ObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream_readFields(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readFields", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); s.reset(); new TestObjectInputStream_readUnshared(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readUnshared", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { FileChannel sourceChannel = new FileInputStream(src).getChannel(); FileChannel destinationChannel = new FileOutputStream(dst).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public boolean clonarFichero(String rutaFicheroOrigen, String rutaFicheroDestino) { System.out.println(""); System.out.println("*********** DENTRO DE 'clonarFichero' ***********"); boolean estado = false; try { FileInputStream entrada = new FileInputStream(rutaFicheroOrigen); FileOutputStream salida = new FileOutputStream(rutaFicheroDestino); FileChannel canalOrigen = entrada.getChannel(); FileChannel canalDestino = salida.getChannel(); canalOrigen.transferTo(0, canalOrigen.size(), canalDestino); entrada.close(); salida.close(); estado = true; } catch (IOException e) { System.out.println("No se encontro el archivo"); e.printStackTrace(); estado = false; } return estado; }
11
Code Sample 1: public Writer createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new OutputStreamWriter(zos, "UTF-8"); } Code Sample 2: private static void zip(File d) throws FileNotFoundException, IOException { String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(d.getParent() + File.separator + "dist.zip"))); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); int skipl = d.getCanonicalPath().length(); ZipEntry entry = new ZipEntry(f.getPath().substring(skipl)); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); FileUtils.moveFile(new File(d.getParent() + File.separator + "dist.zip"), new File(d + File.separator + "dist.zip")); }
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: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static boolean copyFile(File 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: protected void setUp() throws Exception { testOutputDirectory = new File(getClass().getResource("/").getPath()); zipFile = new File(this.testOutputDirectory, "/plugin.zip"); zipOutputDirectory = new File(this.testOutputDirectory, "zip"); zipOutputDirectory.mkdir(); logger.fine("zip dir created"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry("css/")); zos.putNextEntry(new ZipEntry("css/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("js/")); zos.putNextEntry(new ZipEntry("js/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); 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/mylib.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/mylib.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(); }
11
Code Sample 1: public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } } Code Sample 2: private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { InputStream reader = null; ByteArrayOutputStream sw = new ByteArrayOutputStream(); try { reader = new FileInputStream(path); IOUtils.copy(reader, sw); } catch (Exception e) { LOGGER.error("fail to read file - " + path, e); throw new PersistenceException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error("fail to close reader", e); } } } return sw.toByteArray(); } Code Sample 2: public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: public void downSync(Vector v) throws SQLException { try { con = allocateConnection(tableName); PreparedStatement update = con.prepareStatement("update cal_Event set owner=?,subject=?,text=?,place=?," + "contactperson=?,startdate=?,enddate=?,starttime=?,endtime=?,allday=?," + "syncstatus=?,dirtybits=? where OId=? and syncstatus=?"); PreparedStatement insert = con.prepareStatement("insert into cal_Event (owner,subject,text,place," + "contactperson,startdate,enddate,starttime,endtime,allday,syncstatus," + "dirtybits) values(?,?,?,?,?,?,?,?,?,?,?,?)"); PreparedStatement insert1 = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "cal_Event", "newoid")); PreparedStatement delete1 = con.prepareStatement("delete from cal_Event_Remind where event=?"); PreparedStatement delete2 = con.prepareStatement("delete from cal_Event where OId=? " + "and (syncstatus=? or syncstatus=?)"); for (int i = 0; i < v.size(); i++) { try { DO = (EventDO) v.elementAt(i); if (DO.getSyncstatus() == INSERT) { insert.setBigDecimal(1, DO.getOwner()); insert.setString(2, DO.getSubject()); insert.setString(3, DO.getText()); insert.setString(4, DO.getPlace()); insert.setString(5, DO.getContactperson()); insert.setDate(6, DO.getStartdate()); insert.setDate(7, DO.getEnddate()); insert.setTime(8, DO.getStarttime()); insert.setTime(9, DO.getEndtime()); insert.setBoolean(10, DO.getAllday()); insert.setInt(11, RESET); insert.setInt(12, RESET); con.executeUpdate(insert, null); con.reset(); rs = con.executeQuery(insert1, null); if (rs.next()) DO.setOId(rs.getBigDecimal("newoid")); con.reset(); } else if (DO.getSyncstatus() == UPDATE) { update.setBigDecimal(1, DO.getOwner()); update.setString(2, DO.getSubject()); update.setString(3, DO.getText()); update.setString(4, DO.getPlace()); update.setString(5, DO.getContactperson()); update.setDate(6, DO.getStartdate()); update.setDate(7, DO.getEnddate()); update.setTime(8, DO.getStarttime()); update.setTime(9, DO.getEndtime()); update.setBoolean(10, DO.getAllday()); update.setInt(11, RESET); update.setInt(12, RESET); update.setBigDecimal(13, DO.getOId()); update.setInt(14, RESET); con.executeUpdate(update, null); con.reset(); } else if (DO.getSyncstatus() == DELETE) { try { con.setAutoCommit(false); delete1.setBigDecimal(1, DO.getOId()); con.executeUpdate(delete1, null); delete2.setBigDecimal(1, DO.getOId()); delete2.setInt(2, RESET); delete2.setInt(3, DELETE); if (con.executeUpdate(delete2, null) < 1) { con.rollback(); } else { con.commit(); } } catch (Exception e) { con.rollback(); throw e; } finally { con.reset(); } } } catch (Exception e) { if (DO != null) logError("Sync-EventDO.owner = " + DO.getOwner().toString() + " oid = " + (DO.getOId() != null ? DO.getOId().toString() : "NULL"), e); } } if (rs != null) { rs.close(); } } catch (SQLException e) { if (DEBUG) logError("", e); throw e; } finally { release(); } } Code Sample 2: public void add(Site site) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sqlStr = "insert into t_ip_site (id,name,description,ascii_name,site_path,remark_number,increment_index,use_status,appserver_id) VALUES(?,?,?,?,?,?,?,?,?)"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, site.getSiteID()); preparedStatement.setString(2, site.getName()); preparedStatement.setString(3, site.getDescription()); preparedStatement.setString(4, site.getAsciiName()); preparedStatement.setString(5, site.getPath()); preparedStatement.setInt(6, site.getRemarkNumber()); preparedStatement.setString(7, site.getIncrementIndex().trim()); preparedStatement.setString(8, String.valueOf(site.getUseStatus())); preparedStatement.setString(9, String.valueOf(site.getAppserverID())); preparedStatement.executeUpdate(); String[] path = new String[1]; path[0] = site.getPath(); selfDefineAdd(path, site, connection, preparedStatement); connection.commit(); int resID = site.getSiteID() + Const.SITE_TYPE_RES; String resName = site.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); site.wirteFile(); } catch (SQLException ex) { connection.rollback(); log.error("����վ��ʧ��!", ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
00
Code Sample 1: public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } 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 { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } } Code Sample 2: public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
00
Code Sample 1: public static boolean copyFile(String source, String destination, boolean replace) { File sourceFile = new File(source); File destinationFile = new File(destination); if (sourceFile.isDirectory() || destinationFile.isDirectory()) return false; if (destinationFile.isFile() && !replace) return false; if (!sourceFile.isFile()) return false; if (replace) destinationFile.delete(); try { File dir = destinationFile.getParentFile(); while (dir != null && !dir.exists()) { dir.mkdir(); } DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile), 10240)); DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(sourceFile), 10240)); try { while (inStream.available() > 0) { outStream.write(inStream.readUnsignedByte()); } } catch (EOFException eof) { } inStream.close(); outStream.close(); } catch (IOException ex) { throw new FailedException("Failed to copy file " + sourceFile.getAbsolutePath() + " to " + destinationFile.getAbsolutePath(), ex).setFile(destinationFile.getAbsolutePath()); } return true; } Code Sample 2: private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; BOTLObjectSourceDiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((BOTLObjectSourceDiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } }
00
Code Sample 1: protected StringBuffer readURL(java.net.URL url) throws IOException { StringBuffer result = new StringBuffer(4096); InputStreamReader reader = new InputStreamReader(url.openStream()); for (; ; ) { char portion[] = new char[4096]; int numRead = reader.read(portion, 0, portion.length); if (numRead < 0) break; result.append(portion, 0, numRead); } dout("Read " + result.length() + " bytes."); return result; } Code Sample 2: public static void copyHttpContent(final String url, final File outputFile, UsernamePasswordCredentials creds) throws IOException { if (outputFile.exists() && outputFile.isDirectory()) return; String outputFilePath = outputFile.getAbsolutePath(); String outputFilePathTemp = outputFilePath + ".tmp"; File tmpDownloadFile = FileUtil.createNewFile(outputFilePathTemp, false); if (!tmpDownloadFile.isFile()) return; MyFileLock fl = FileUtil.tryLockTempFile(tmpDownloadFile, 1000, ShareConstants.connectTimeout); if (fl != null) { try { long contentLength = -1; long lastModified = -1; OutputStream out = null; InputStream in = null; HttpClient httpclient = createHttpClient(creds); try { HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode() / 100; if (status == 2) { HttpEntity entity = response.getEntity(); if (entity != null) { Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (lastModifiedHeader != null) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US)); try { lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime(); } catch (ParseException e) { logger.error(e); } } in = entity.getContent(); out = new BufferedOutputStream(new FileOutputStream(tmpDownloadFile)); IOUtil.copyStreams(in, out); } } } catch (Exception e) { logger.error("Get HTTP File ERROR:" + url, e); } finally { IOUtil.close(in); IOUtil.close(out); httpclient.getConnectionManager().shutdown(); } if (tmpDownloadFile.isFile()) { if ((contentLength == -1 && tmpDownloadFile.length() > 0) || tmpDownloadFile.length() == contentLength) { IOUtil.copyFile(tmpDownloadFile, outputFile); if (lastModified > 0) outputFile.setLastModified(lastModified); } } } finally { tmpDownloadFile.delete(); fl.release(); } } }
00
Code Sample 1: public static String sha1(String clearText, String seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update((seed + clearText).getBytes()); return convertToHex(md.digest()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } Code Sample 2: private List loadPluginFromDir(File directory, boolean bSkipAlreadyLoaded, boolean loading_for_startup, boolean initialise) throws PluginException { List loaded_pis = new ArrayList(); ClassLoader plugin_class_loader = root_class_loader; if (!directory.isDirectory()) { return (loaded_pis); } String pluginName = directory.getName(); File[] pluginContents = directory.listFiles(); if (pluginContents == null || pluginContents.length == 0) { return (loaded_pis); } boolean looks_like_plugin = false; for (int i = 0; i < pluginContents.length; i++) { String name = pluginContents[i].getName().toLowerCase(); if (name.endsWith(".jar") || name.equals("plugin.properties")) { looks_like_plugin = true; break; } } if (!looks_like_plugin) { if (Logger.isEnabled()) Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Plugin directory '" + directory + "' has no plugin.properties " + "or .jar files, skipping")); return (loaded_pis); } String[] plugin_version = { null }; String[] plugin_id = { null }; pluginContents = PluginLauncherImpl.getHighestJarVersions(pluginContents, plugin_version, plugin_id, true); for (int i = 0; i < pluginContents.length; i++) { File jar_file = pluginContents[i]; if (pluginContents.length > 1) { String name = jar_file.getName(); if (name.startsWith("i18nPlugin_")) { if (Logger.isEnabled()) Logger.log(new LogEvent(LOGID, "renaming '" + name + "' to conform with versioning system")); jar_file.renameTo(new File(jar_file.getParent(), "i18nAZ_0.1.jar ")); continue; } } plugin_class_loader = PluginLauncherImpl.addFileToClassPath(root_class_loader, plugin_class_loader, jar_file); } String plugin_class_string = null; try { Properties props = new Properties(); File properties_file = new File(directory.toString() + File.separator + "plugin.properties"); try { if (properties_file.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(properties_file); props.load(fis); } finally { if (fis != null) { fis.close(); } } } else { if (plugin_class_loader instanceof URLClassLoader) { URLClassLoader current = (URLClassLoader) plugin_class_loader; URL url = current.findResource("plugin.properties"); if (url != null) { URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); props.load(is); } else { throw (new Exception("failed to load plugin.properties from jars")); } } else { throw (new Exception("failed to load plugin.properties from dir or jars")); } } } catch (Throwable e) { Debug.printStackTrace(e); String msg = "Can't read 'plugin.properties' for plugin '" + pluginName + "': file may be missing"; Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, msg)); System.out.println(msg); throw (new PluginException(msg, e)); } checkJDKVersion(pluginName, props, true); checkAzureusVersion(pluginName, props, true); plugin_class_string = (String) props.get("plugin.class"); if (plugin_class_string == null) { plugin_class_string = (String) props.get("plugin.classes"); if (plugin_class_string == null) { plugin_class_string = ""; } } String plugin_name_string = (String) props.get("plugin.name"); if (plugin_name_string == null) { plugin_name_string = (String) props.get("plugin.names"); } int pos1 = 0; int pos2 = 0; while (true) { int p1 = plugin_class_string.indexOf(";", pos1); String plugin_class; if (p1 == -1) { plugin_class = plugin_class_string.substring(pos1).trim(); } else { plugin_class = plugin_class_string.substring(pos1, p1).trim(); pos1 = p1 + 1; } PluginInterfaceImpl existing_pi = getPluginFromClass(plugin_class); if (existing_pi != null) { if (bSkipAlreadyLoaded) { break; } File this_parent = directory.getParentFile(); File existing_parent = null; if (existing_pi.getInitializerKey() instanceof File) { existing_parent = ((File) existing_pi.getInitializerKey()).getParentFile(); } if (this_parent.equals(FileUtil.getApplicationFile("plugins")) && existing_parent != null && existing_parent.equals(FileUtil.getUserFile("plugins"))) { if (Logger.isEnabled()) Logger.log(new LogEvent(LOGID, "Plugin '" + plugin_name_string + "/" + plugin_class + ": shared version overridden by user-specific one")); return (new ArrayList()); } else { Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_WARNING, "Error loading '" + plugin_name_string + "', plugin class '" + plugin_class + "' is already loaded")); } } else { String plugin_name = null; if (plugin_name_string != null) { int p2 = plugin_name_string.indexOf(";", pos2); if (p2 == -1) { plugin_name = plugin_name_string.substring(pos2).trim(); } else { plugin_name = plugin_name_string.substring(pos2, p2).trim(); pos2 = p2 + 1; } } Properties new_props = (Properties) props.clone(); for (int j = 0; j < default_version_details.length; j++) { if (plugin_class.equals(default_version_details[j][0])) { if (new_props.get("plugin.id") == null) { new_props.put("plugin.id", default_version_details[j][1]); } if (plugin_name == null) { plugin_name = default_version_details[j][2]; } if (new_props.get("plugin.version") == null) { if (plugin_version[0] != null) { new_props.put("plugin.version", plugin_version[0]); } else { new_props.put("plugin.version", default_version_details[j][3]); } } } } new_props.put("plugin.class", plugin_class); if (plugin_name != null) { new_props.put("plugin.name", plugin_name); } Throwable load_failure = null; String pid = plugin_id[0] == null ? directory.getName() : plugin_id[0]; List<File> verified_files = null; Plugin plugin = null; if (vc_disabled_plugins.contains(pid)) { log("Plugin '" + pid + "' has been administratively disabled"); } else { if (pid.endsWith("_v")) { verified_files = new ArrayList<File>(); log("Re-verifying " + pid); for (int i = 0; i < pluginContents.length; i++) { File jar_file = pluginContents[i]; if (jar_file.getName().endsWith(".jar")) { try { log(" verifying " + jar_file); AEVerifier.verifyData(jar_file); verified_files.add(jar_file); log(" OK"); } catch (Throwable e) { String msg = "Error loading plugin '" + pluginName + "' / '" + plugin_class_string + "'"; Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, e)); plugin = new FailedPlugin(plugin_name, directory.getAbsolutePath()); } } } } if (plugin == null) { plugin = PluginLauncherImpl.getPreloadedPlugin(plugin_class); if (plugin == null) { try { Class c = plugin_class_loader.loadClass(plugin_class); plugin = (Plugin) c.newInstance(); } catch (java.lang.UnsupportedClassVersionError e) { plugin = new FailedPlugin(plugin_name, directory.getAbsolutePath()); load_failure = new UnsupportedClassVersionError(e.getMessage()); } catch (Throwable e) { if (e instanceof ClassNotFoundException && props.getProperty("plugin.install_if_missing", "no").equalsIgnoreCase("yes")) { } else { load_failure = e; } plugin = new FailedPlugin(plugin_name, directory.getAbsolutePath()); } } else { plugin_class_loader = plugin.getClass().getClassLoader(); } } MessageText.integratePluginMessages((String) props.get("plugin.langfile"), plugin_class_loader); PluginInterfaceImpl plugin_interface = new PluginInterfaceImpl(plugin, this, directory, plugin_class_loader, verified_files, directory.getName(), new_props, directory.getAbsolutePath(), pid, plugin_version[0]); boolean bEnabled = (loading_for_startup) ? plugin_interface.getPluginState().isLoadedAtStartup() : initialise; plugin_interface.getPluginState().setDisabled(!bEnabled); try { Method load_method = plugin.getClass().getMethod("load", new Class[] { PluginInterface.class }); load_method.invoke(plugin, new Object[] { plugin_interface }); } catch (NoSuchMethodException e) { } catch (Throwable e) { load_failure = e; } loaded_pis.add(plugin_interface); if (load_failure != null) { plugin_interface.setAsFailed(); if (!pid.equals(UpdaterUpdateChecker.getPluginID())) { String msg = "Error loading plugin '" + pluginName + "' / '" + plugin_class_string + "'"; LogAlert la; if (load_failure instanceof UnsupportedClassVersionError) { la = new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, msg + ". " + MessageText.getString("plugin.install.class_version_error")); } else { la = new LogAlert(LogAlert.UNREPEATABLE, msg, load_failure); } Logger.log(la); System.out.println(msg + ": " + load_failure); } } } } if (p1 == -1) { break; } } return (loaded_pis); } catch (Throwable e) { if (e instanceof PluginException) { throw ((PluginException) e); } Debug.printStackTrace(e); String msg = "Error loading plugin '" + pluginName + "' / '" + plugin_class_string + "'"; Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, e)); System.out.println(msg + ": " + e); throw (new PluginException(msg, e)); } }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public static void parseRDFXML(String url, StatementHandler handler) throws IOException { ARP parser = new ARP(); parser.getHandlers().setStatementHandler(handler); URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); InputStream in = null; try { in = conn.getInputStream(); if (encoding == null) parser.load(in, url); else parser.load(new InputStreamReader(in, encoding), url); in.close(); } catch (org.xml.sax.SAXException e) { throw new OntopiaRuntimeException(e); } finally { if (in != null) in.close(); } }
11
Code Sample 1: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; } Code Sample 2: public void postProcess() throws StopWriterVisitorException { dbfWriter.postProcess(); try { short originalEncoding = dbf.getDbaseHeader().getLanguageID(); File dbfFile = fTemp; FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel(); FileChannel fcoutDbf = new FileOutputStream(file).getChannel(); DriverUtilities.copy(fcinDbf, fcoutDbf); fTemp.delete(); close(); RandomAccessFile fo = new RandomAccessFile(file, "rw"); fo.seek(29); fo.writeByte(originalEncoding); fo.close(); open(file); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } catch (CloseDriverException e) { throw new StopWriterVisitorException(getName(), e); } catch (OpenDriverException e) { throw new StopWriterVisitorException(getName(), e); } }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: protected Icon newIcon(String iconName) { URL url = Utils.getResource(getFullPath(iconName, "/"), getClass()); if (url == null) { if (getParent() != null) return getParent().getIcon(iconName); return null; } try { MethodCall getImage = new MethodCaller("org.apache.sanselan.Sanselan", null, "getBufferedImage", new Object[] { InputStream.class }).getMethodCall(); getImage.setArgumentValue(0, url.openStream()); return new ImageIcon((BufferedImage) getImage.call()); } catch (Throwable e) { return new ImageIcon(url); } } Code Sample 2: protected Model loadModel(URL url, String filenameBase, SourceModelType modelType, URL baseURL, String skin, float scale, int flags, AppearanceFactory appFactory, GeometryFactory geomFactory, NodeFactory nodeFactory, AnimationFactory animFactory, SpecialItemsHandler siHandler, Model model) throws IOException, IncorrectFormatException, ParsingException { boolean convertZup2Yup = modelType.getConvertFlag(flags); switch(modelType) { case AC3D: AC3DPrototypeLoader.load(url.openStream(), baseURL, appFactory, geomFactory, nodeFactory, true, model, siHandler); break; case ASE: AseReader.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case BSP: BSPPrototypeLoader.load(url.openStream(), filenameBase, baseURL, geomFactory, true, 0.03f, appFactory, nodeFactory, model, GroupType.BSP_TREE, siHandler); break; case CAL3D: break; case COLLADA: convertZup2Yup = true; COLLADALoader.load(baseURL, url.openStream(), appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD2: MD2File.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD3: MD3File.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD5: { Object[][][] boneWeights = MD5MeshReader.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); ((SpecialItemsHandlerImpl) siHandler).flush(); List<URL> animResources = new ResourceLocator(baseURL).findAllResources("md5anim", true, false); for (URL animURL : animResources) { String filename = LoaderUtils.extractFilenameWithoutExt(animURL); MD5AnimationReader.load(animURL.openStream(), filename, baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, model.getShapes(), boneWeights, animFactory, siHandler, model); } } break; case MS3D: break; case OBJ: GroupNode rootGroup = model; if (scale != 1.0f) { TransformGroup scaleGroup = new TransformGroup(); scaleGroup.getTransform().setScale(scale); model.addChild(scaleGroup); model.setMainGroup(scaleGroup); rootGroup = scaleGroup; } OBJPrototypeLoader.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, siHandler, rootGroup); break; case TDS: TDSFile.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, nodeFactory, animFactory, siHandler, model); } return (model); }
11
Code Sample 1: public static void main(String arg[]) { try { URL url = new URL(tempurl); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); connect.setDoInput(true); connect.setDoOutput(true); BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream(), "gb2312")); String line = null; StringBuffer content = new StringBuffer(); while ((line = in.readLine()) != null) { content.append(line); } in.close(); url = null; String msg = content.toString(); Matcher m = p.matcher(msg); while (m.find()) { System.out.println(m.group(1) + "---" + m.group(2) + "---" + m.group(3) + "---" + m.group(4) + "---" + m.group(5) + "---"); } } catch (Exception e) { System.out.println("Error:"); System.out.println(e.getStackTrace()); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static GCalendar getNewestCalendar(Calendar startDate) throws IOException { GCalendar hoge = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpClient http = new DefaultHttpClient(); HttpGet method = new HttpGet("http://localhost:8080/GoogleCalendar/select"); HttpResponse response = http.execute(method); String jsonstr = response.getEntity().toString(); System.out.println("jsonstr = " + jsonstr); hoge = JSON.decode(jsonstr, GCalendar.class); } catch (Exception ex) { ex.printStackTrace(); } return hoge; } Code Sample 2: public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
00
Code Sample 1: String getLatestVersion() { try { URL url = new URL(Constants.VERSION_FILE_URL); URLConnection connection = url.openConnection(); connection.setConnectTimeout(15000); InputStream in = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); return br.readLine(); } catch (Exception ex) { return null; } } Code Sample 2: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } }
11
Code Sample 1: private static void copyFile(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); FileChannel inc = in.getChannel(); FileChannel outc = out.getChannel(); inc.transferTo(0, inc.size(), outc); inc.close(); outc.close(); in.close(); out.close(); } catch (Exception e) { } } Code Sample 2: public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: private static void init() { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> enumeration = cl.getResources("extension-services.properties"); do { if (!enumeration.hasMoreElements()) break; URL url = (URL) enumeration.nextElement(); System.out.println(" - " + url); try { props = new Properties(); props.load(url.openStream()); } catch (Exception e) { e.printStackTrace(); } } while (true); } catch (IOException e) { } }
11
Code Sample 1: public boolean saveVideoXMLOnWebserver() { String text = ""; boolean erg = false; try { URL url = new URL("http://localhost:8080/virtPresenterVerwalter/videofile.jsp?id=" + this.getId()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String zeile = ""; while ((zeile = in.readLine()) != null) { text += zeile + "\n"; } in.close(); http.disconnect(); erg = saveVideoXMLOnWebserver(text); System.err.println("Job " + this.getId() + " erfolgreich bearbeitet!"); } catch (MalformedURLException e) { System.err.println("Job " + this.getId() + ": Konnte video.xml nicht erstellen. Verbindung konnte nicht aufgebaut werden."); return false; } catch (IOException e) { System.err.println("Job " + this.getId() + ": Konnte video.xml nicht erstellen. Konnte Daten nicht lesen/schreiben."); return false; } return erg; } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public void delete(String user) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from Principals where PrincipalId = '" + user + "'"); stmt.executeUpdate("delete from Roles where PrincipalId = '" + user + "'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: public String parse(String queryText) throws ParseException { try { StringBuilder sb = new StringBuilder(); queryText = Val.chkStr(queryText); if (queryText.length() > 0) { URL url = new URL(getUrl(queryText)); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } } return sb.toString(); } catch (IOException ex) { throw new ParseException("Ontology parser is unable to parse term: \"" + queryText + "\" due to internal error: " + ex.getMessage()); } } Code Sample 2: public static synchronized Integer getNextSequence(String seqNum) throws ApplicationException { Connection dbConn = null; java.sql.PreparedStatement preStat = null; java.sql.ResultSet rs = null; boolean noTableMatchFlag = false; int currID = 0; int nextID = 0; try { dbConn = getConnection(); } catch (Exception e) { log.error("Error Getting Connection.", e); throw new ApplicationException("errors.framework.db_conn", e); } synchronized (hashPkKeyLock) { if (hashPkKeyLock.get(seqNum) == null) { hashPkKeyLock.put(seqNum, new Object()); } } synchronized (hashPkKeyLock.get(seqNum)) { synchronized (dbConn) { try { preStat = dbConn.prepareStatement("SELECT TABLE_KEY_MAX FROM SYS_TABLE_KEY WHERE TABLE_NAME=?"); preStat.setString(1, seqNum); rs = preStat.executeQuery(); if (rs.next()) { currID = rs.getInt(1); } else { noTableMatchFlag = true; } } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { rs.close(); } catch (Exception ignore) { } finally { rs = null; } try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } if (noTableMatchFlag) { try { currID = 0; preStat = dbConn.prepareStatement("INSERT INTO SYS_TABLE_KEY(TABLE_NAME, TABLE_KEY_MAX) VALUES(?, ?)", java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); preStat.setString(1, seqNum); preStat.setInt(2, currID); preStat.executeUpdate(); } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } try { int updateCnt = 0; nextID = currID; do { nextID++; preStat = dbConn.prepareStatement("UPDATE SYS_TABLE_KEY SET TABLE_KEY_MAX=? WHERE TABLE_NAME=? AND TABLE_KEY_MAX=?", java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); preStat.setInt(1, nextID); preStat.setString(2, seqNum); preStat.setInt(3, currID); updateCnt = preStat.executeUpdate(); currID++; if (updateCnt == 0 && (currID % 2) == 0) { Thread.sleep(50); } } while (updateCnt == 0); dbConn.commit(); return (new Integer(nextID)); } catch (Exception e) { log.error(e, e); try { dbConn.rollback(); } catch (Exception ignore) { } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } } } } }
00
Code Sample 1: public void init(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8"), 0, password.length()); byte[] rawKey = md.digest(); skeySpec = new SecretKeySpec(rawKey, "AES"); ivSpec = new IvParameterSpec(rawKey); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: @Override public void start() { System.err.println("start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); super.start(); model = new ApplicationModel(); model.setExceptionHandler(new ExceptionHandler() { public void handle(Throwable t) { t.printStackTrace(); } public void handleUncaught(Throwable t) { t.printStackTrace(); } }); model.setApplet(true); model.dom.getOptions().setAutolayout(false); System.err.println("ApplicationModel created @ " + (System.currentTimeMillis() - t0) + " msec"); model.addDasPeersToApp(); System.err.println("done addDasPeersToApp @ " + (System.currentTimeMillis() - t0) + " msec"); try { System.err.println("Formatters: " + DataSourceRegistry.getInstance().getFormatterExtensions()); } catch (Exception ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } ApplicationModel appmodel = model; dom = model.getDocumentModel(); String debug = getParameter("debug"); if (debug != null && !debug.equals("true")) { } int width = getIntParameter("width", 700); int height = getIntParameter("height", 400); String fontParam = getStringParameter("font", ""); String column = getStringParameter("column", ""); String row = getStringParameter("row", ""); String scolor = getStringParameter("color", ""); String srenderType = getStringParameter("renderType", ""); String stimeRange = getStringParameter("timeRange", ""); String sfillColor = getStringParameter("fillColor", ""); String sforegroundColor = getStringParameter("foregroundColor", ""); String sbackgroundColor = getStringParameter("backgroundColor", ""); String title = getStringParameter("plot.title", ""); String xlabel = getStringParameter("plot.xaxis.label", ""); String xrange = getStringParameter("plot.xaxis.range", ""); String xlog = getStringParameter("plot.xaxis.log", ""); String xdrawTickLabels = getStringParameter("plot.xaxis.drawTickLabels", ""); String ylabel = getStringParameter("plot.yaxis.label", ""); String yrange = getStringParameter("plot.yaxis.range", ""); String ylog = getStringParameter("plot.yaxis.log", ""); String ydrawTickLabels = getStringParameter("plot.yaxis.drawTickLabels", ""); String zlabel = getStringParameter("plot.zaxis.label", ""); String zrange = getStringParameter("plot.zaxis.range", ""); String zlog = getStringParameter("plot.zaxis.log", ""); String zdrawTickLabels = getStringParameter("plot.zaxis.drawTickLabels", ""); statusCallback = getStringParameter("statusCallback", ""); timeCallback = getStringParameter("timeCallback", ""); clickCallback = getStringParameter("clickCallback", ""); if (srenderType.equals("fill_to_zero")) { srenderType = "fillToZero"; } setInitializationStatus("readParameters"); System.err.println("done readParameters @ " + (System.currentTimeMillis() - t0) + " msec"); String vap = getParameter("vap"); if (vap != null) { InputStream in = null; try { URL url = new URL(vap); System.err.println("load vap " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); in = url.openStream(); System.err.println("open vap stream " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.doOpen(in, null); System.err.println("done open vap @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.waitUntilIdle(false); System.err.println("done load vap and waitUntilIdle @ " + (System.currentTimeMillis() - t0) + " msec"); Canvas cc = appmodel.getDocumentModel().getCanvases(0); System.err.println("vap height, width= " + cc.getHeight() + "," + cc.getWidth()); width = getIntParameter("width", cc.getWidth()); height = getIntParameter("height", cc.getHeight()); System.err.println("output height, width= " + width + "," + height); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } } appmodel.getCanvas().setSize(width, height); appmodel.getCanvas().revalidate(); appmodel.getCanvas().setPrintingTag(""); dom.getOptions().setAutolayout("true".equals(getParameter("autolayout"))); if (!dom.getOptions().isAutolayout() && vap == null) { if (!row.equals("")) { dom.getController().getCanvas().getController().setRow(row); } if (!column.equals("")) { dom.getController().getCanvas().getController().setColumn(column); } dom.getCanvases(0).getRows(0).setTop("0%"); dom.getCanvases(0).getRows(0).setBottom("100%"); } if (!fontParam.equals("")) { appmodel.canvas.setBaseFont(Font.decode(fontParam)); } JMenuItem item; item = new JMenuItem(new AbstractAction("Reset Zoom") { public void actionPerformed(ActionEvent e) { resetZoom(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(item); overviewMenuItem = new JCheckBoxMenuItem(new AbstractAction("Context Overview") { public void actionPerformed(ActionEvent e) { addOverview(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(overviewMenuItem); if (sforegroundColor != null && !sforegroundColor.equals("")) { appmodel.canvas.setForeground(Color.decode(sforegroundColor)); } if (sbackgroundColor != null && !sbackgroundColor.equals("")) { appmodel.canvas.setBackground(Color.decode(sbackgroundColor)); } getContentPane().setLayout(new BorderLayout()); System.err.println("done set parameters @ " + (System.currentTimeMillis() - t0) + " msec"); String surl = getParameter("url"); String process = getStringParameter("process", ""); String script = getStringParameter("script", ""); if (surl == null) { surl = getParameter("dataSetURL"); } if (surl != null && !surl.equals("")) { DataSource dsource; try { dsource = DataSetURI.getDataSource(surl); System.err.println("get dsource for " + surl + " @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" got dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); } catch (NullPointerException ex) { throw new RuntimeException("No such data source: ", ex); } catch (Exception ex) { ex.printStackTrace(); dsource = null; } DatumRange timeRange1 = null; if (!stimeRange.equals("")) { timeRange1 = DatumRangeUtil.parseTimeRangeValid(stimeRange); TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb != null) { System.err.println("do tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); tsb.setTimeRange(timeRange1); System.err.println("done tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); } } QDataSet ds; if (dsource != null) { TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb == null) { try { System.err.println("do getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); if (dsource.getClass().toString().contains("CsvDataSource")) System.err.println(" WHY IS THIS CsvDataSource!?!?"); ds = dsource == null ? null : dsource.getDataSet(loadInitialMonitor); for (int i = 0; i < Math.min(12, ds.length()); i++) { System.err.printf("ds[%d]=%s\n", i, ds.slice(i)); } System.err.println("loaded ds: " + ds); System.err.println("done getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (Exception ex) { throw new RuntimeException(ex); } } } System.err.println("do setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.setDataSource(dsource); System.err.println("done setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("dataSourceSet"); if (stimeRange != null && !stimeRange.equals("")) { try { System.err.println("wait for idle @ " + (System.currentTimeMillis() - t0) + " msec (due to stimeRange)"); appmodel.waitUntilIdle(true); System.err.println("done wait for idle @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } if (UnitsUtil.isTimeLocation(dom.getTimeRange().getUnits())) { dom.setTimeRange(timeRange1); } } setInitializationStatus("dataSetLoaded"); } System.err.println("done dataSetLoaded @ " + (System.currentTimeMillis() - t0) + " msec"); Plot p = dom.getController().getPlot(); if (!title.equals("")) { p.setTitle(title); } Axis axis = p.getXaxis(); if (!xlabel.equals("")) { axis.setLabel(xlabel); } if (!xrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(xrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!xlog.equals("")) { axis.setLog("true".equals(xlog)); } if (!xdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(xdrawTickLabels)); } axis = p.getYaxis(); if (!ylabel.equals("")) { axis.setLabel(ylabel); } if (!yrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(yrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!ylog.equals("")) { axis.setLog("true".equals(ylog)); } if (!ydrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(ydrawTickLabels)); } axis = p.getZaxis(); if (!zlabel.equals("")) { axis.setLabel(zlabel); } if (!zrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(zrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!zlog.equals("")) { axis.setLog("true".equals(zlog)); } if (!zdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(zdrawTickLabels)); } if (srenderType != null && !srenderType.equals("")) { try { RenderType renderType = RenderType.valueOf(srenderType); dom.getController().getPlotElement().setRenderType(renderType); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } } System.err.println("done setRenderType @ " + (System.currentTimeMillis() - t0) + " msec"); if (!scolor.equals("")) { try { dom.getController().getPlotElement().getStyle().setColor(Color.decode(scolor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sfillColor.equals("")) { try { dom.getController().getPlotElement().getStyle().setFillColor(Color.decode(sfillColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sforegroundColor.equals("")) { try { dom.getOptions().setForeground(Color.decode(sforegroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sbackgroundColor.equals("")) { try { dom.getOptions().setBackground(Color.decode(sbackgroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } surl = getParameter("dataSetURL"); if (surl != null) { if (surl.startsWith("about:")) { setDataSetURL(surl); } else { } } getContentPane().remove(progressComponent); getContentPane().add(model.getCanvas()); System.err.println("done add to applet @ " + (System.currentTimeMillis() - t0) + " msec"); validate(); System.err.println("done applet.validate @ " + (System.currentTimeMillis() - t0) + " msec"); repaint(); appmodel.getCanvas().setVisible(true); initializing = false; repaint(); System.err.println("ready @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("ready"); dom.getController().getPlot().getXaxis().addPropertyChangeListener(Axis.PROP_RANGE, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { timeCallback(String.valueOf(evt.getNewValue())); } }); if (!clickCallback.equals("")) { String clickCallbackLabel = "Applet Click"; int i = clickCallback.indexOf(","); if (i != -1) { int i2 = clickCallback.indexOf("label="); if (i2 != -1) clickCallbackLabel = clickCallback.substring(i2 + 6).trim(); clickCallback = clickCallback.substring(0, i).trim(); } final DasPlot plot = dom.getPlots(0).getController().getDasPlot(); MouseModule mm = new MouseModule(plot, new CrossHairRenderer(plot, null, plot.getXAxis(), plot.getYAxis()), clickCallbackLabel) { @Override public void mousePressed(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseDragged(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseReleased(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } }; plot.getDasMouseInputAdapter().setPrimaryModule(mm); } p.getController().getDasPlot().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getXaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getYaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getZaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); if (getStringParameter("contextOverview", "off").equals("on")) { Runnable run = new Runnable() { public void run() { dom.getController().waitUntilIdle(); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } dom.getController().waitUntilIdle(); doSetOverview(true); } }; new Thread(run).start(); } System.err.println("done start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); }
00
Code Sample 1: public static boolean delete(String url, int ip, int port) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("DELETE"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.connect(); return request.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public Result request(URL url) { try { return xmlUtil.unmarshall(urlOpener.openStream(url)); } catch (FileNotFoundException e) { log.info("File not found: " + url); } catch (IOException e) { log.error("Failed to read from url: " + url + ". " + e.getMessage(), e); } return null; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
00
Code Sample 1: public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout, Map<String, String> headers) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); if (username != null || password != null) { byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } Code Sample 2: public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { LOG.debug("[sgkim] copy - start"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in = null; OutputStream out = null; try { LOG.debug("[sgkim] srcFS: " + srcFS + ", src: " + src); in = srcFS.open(src); LOG.debug("[sgkim] dstFS: " + dstFS + ", dst: " + dst); out = dstFS.create(dst, overwrite); LOG.debug("[sgkim] copyBytes - start"); IOUtils.copyBytes(in, out, conf, true); LOG.debug("[sgkim] copyBytes - end"); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } LOG.debug("[sgkim] copy - end"); if (deleteSource) { return srcFS.delete(src, true); } else { return true; } }
00
Code Sample 1: private HttpURLConnection getHttpURLConnection(String bizDocToExecute) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void main(String[] args) { FileInputStream fr = null; FileOutputStream fw = null; BufferedInputStream br = null; BufferedOutputStream bw = null; try { fr = new FileInputStream("D:/5.xls"); fw = new FileOutputStream("c:/Dxw.java"); br = new BufferedInputStream(fr); bw = new BufferedOutputStream(fw); int read = br.read(); while (read != -1) { bw.write(read); read = br.read(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public 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: @Override public void exec() { if (fileURI == null) return; InputStream is = null; try { if (fileURI.toLowerCase().startsWith("dbgp://")) { String uri = fileURI.substring(7); if (uri.toLowerCase().startsWith("file/")) { uri = fileURI.substring(5); is = new FileInputStream(new File(uri)); } else { XmldbURI pathUri = XmldbURI.create(URLDecoder.decode(fileURI.substring(15), "UTF-8")); Database db = getJoint().getContext().getDatabase(); DBBroker broker = null; try { broker = db.getBroker(); DocumentImpl resource = broker.getXMLResource(pathUri, Lock.READ_LOCK); if (resource.getResourceType() == DocumentImpl.BINARY_FILE) { is = broker.getBinaryResource((BinaryDocument) resource); } else { return; } } catch (EXistException e) { exception = e; } finally { db.release(broker); } } } else { URL url = new URL(fileURI); URLConnection conn = url.openConnection(); is = conn.getInputStream(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[256]; int c; while ((c = is.read(buf)) > -1) { baos.write(buf, 0, c); } source = baos.toByteArray(); success = true; } catch (MalformedURLException e) { exception = e; } catch (IOException e) { exception = e; } catch (PermissionDeniedException e) { exception = e; } finally { if (is != null) try { is.close(); } catch (IOException e) { if (exception == null) exception = e; } } } Code Sample 2: public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
11
Code Sample 1: char[] DigestCalcHA1(String algorithm, String userName, String realm, String password, String nonce, String clientNonce) throws SaslException { byte[] hash; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(realm.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); hash = md.digest(); if ("md5-sess".equals(algorithm)) { md.update(hash); md.update(":".getBytes("UTF-8")); md.update(nonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(clientNonce.getBytes("UTF-8")); hash = md.digest(); } } catch (NoSuchAlgorithmException e) { throw new SaslException("No provider found for MD5 hash", e); } catch (UnsupportedEncodingException e) { throw new SaslException("UTF-8 encoding not supported by platform.", e); } return convertToHex(hash); } Code Sample 2: public String setEncryptedPassword(String rawPassword) { String out = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(rawPassword.getBytes()); byte raw[] = md.digest(); out = new String(); for (int x = 0; x < raw.length; x++) { String hex2 = Integer.toHexString((int) raw[x] & 0xFF); if (1 == hex2.length()) { hex2 = "0" + hex2; } out += hex2; int a = 1; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return out; }
11
Code Sample 1: @Override public String execute() throws Exception { SystemContext sc = getSystemContext(); if (sc.getExpireTime() == -1) { return LOGIN; } else if (upload != null) { try { Enterprise e = LicenceUtils.get(upload); sc.setEnterpriseName(e.getEnterpriseName()); sc.setExpireTime(e.getExpireTime()); String webPath = ServletActionContext.getServletContext().getRealPath("/"); File desFile = new File(webPath, LicenceUtils.LICENCE_FILE_NAME); FileChannel sourceChannel = new FileInputStream(upload).getChannel(); FileChannel destinationChannel = new FileOutputStream(desFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); return LOGIN; } catch (Exception e) { } } return "license"; } Code Sample 2: public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws WsException { String callback = para(req, JsonWriter.CALLBACK, null); String input = para(req, INPUT, null); String type = para(req, TYPE, "url"); String format = para(req, FORMAT, null); PrintWriter out = null; Reader contentReader = null; try { out = resp.getWriter(); if (StringUtils.trimToNull(input) == null) { resp.setContentType("text/html"); printHelp(out); } else { if (type.equalsIgnoreCase("url")) { HttpGet httpget = new HttpGet(input); try { HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String charset = "UTF-8"; contentReader = new InputStreamReader(entity.getContent(), charset); if (false) { contentReader = new FilterXmlReader(contentReader); } else { contentReader = new BufferedReader(contentReader); } } } catch (RuntimeException ex) { httpget.abort(); throw ex; } } else { contentReader = new StringReader(input); } long time = System.currentTimeMillis(); TokenStream stream = nameTokenStream(contentReader); SciNameIterator iter = new SciNameIterator(stream); if (format != null && format.equalsIgnoreCase("json")) { resp.setContentType("application/json"); streamAsJSON(iter, out, callback); } else if (format != null && format.equalsIgnoreCase("xml")) { resp.setContentType("text/xml"); streamAsXML(iter, out); } else { resp.setContentType("text/plain"); streamAsText(iter, out); } log.info("Indexing finished in " + (System.currentTimeMillis() - time) + " msecs"); } } catch (IOException e1) { log.error("IOException", e1); e1.printStackTrace(); } finally { if (contentReader != null) { try { contentReader.close(); } catch (IOException e) { log.error("IOException", e); } } out.flush(); out.close(); } } Code Sample 2: private CachedQuery loadQuery(String path) throws CacheException, IOException, XQueryException { final URL url; final long lastModified; final InputStream is; try { url = getServletContext().getResource(path); assert (url != null); lastModified = url.openConnection().getLastModified(); is = url.openStream(); } catch (IOException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } _lock.readLock().lock(); CachedQuery cached = _caches.get(path); if (cached == null || cached.loadTimeStamp < lastModified) { if (cached == null) { cached = new CachedQuery(); } XQueryParser parser = new XQueryParser(is); StaticContext staticEnv = parser.getStaticContext(); try { URI baseUri = url.toURI(); staticEnv.setBaseURI(baseUri); } catch (URISyntaxException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); } final XQueryModule module; try { module = parser.parse(); } catch (XQueryException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); _lock.readLock().unlock(); throw e; } _lock.readLock().unlock(); _lock.writeLock().lock(); cached.queryObject = module; cached.staticEnv = staticEnv; cached.loadTimeStamp = System.currentTimeMillis(); _caches.put(path, cached); _lock.writeLock().unlock(); _lock.readLock().lock(); try { module.staticAnalysis(staticEnv); } catch (XQueryException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); _lock.readLock().unlock(); throw e; } } _lock.readLock().unlock(); return cached; }
00
Code Sample 1: @Algorithm(name = "EXT") public void execute() { Connection conn = null; try { Class.forName(jdbcDriver).newInstance(); conn = DriverManager.getConnection(jdbcUrl, username, password); conn.setAutoCommit(false); l.debug("Connected to the database"); Statement stmt = conn.createStatement(); l.debug(sql); ResultSet rs = stmt.executeQuery(sql); List<Map<String, String>> res = DbUtil.listFromRS(rs); if (null != res && !res.isEmpty()) { docs = new ArrayList<Doc>(); List<String> keys = new ArrayList<String>(); for (Map<String, String> map : res) { docs.add(convert(map)); String key = map.get(pk); keys.add(key); } String sql2 = updateSQL + " where " + pk + " in (" + CollectionUtil.toString(keys) + ")"; l.debug(sql2); stmt.executeUpdate(sql2); conn.commit(); } } catch (Exception e) { l.error(e.getMessage(), e); if (null != conn) { try { conn.rollback(); } catch (Exception ex) { l.error(ex.getMessage(), ex); } } throw new RuntimeException(e.getMessage()); } finally { try { if (null != conn) { conn.close(); l.debug("Disconnected from database"); } } catch (Exception ex) { l.error(ex.getMessage(), ex); } } if (null != docs && !docs.isEmpty()) { triggerEvent("EO"); } else { triggerEvent("EMPTY"); } } Code Sample 2: public static synchronized String getPageContent(String pageUrl) { URL url = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String line = null; StringBuilder page = null; if (pageUrl == null || pageUrl.trim().length() == 0) { return null; } else { try { url = new URL(pageUrl); inputStreamReader = new InputStreamReader(url.openStream()); bufferedReader = new BufferedReader(inputStreamReader); page = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } } } if (page == null) { return null; } else { return page.toString(); } }
00
Code Sample 1: public HttpURLConnection getConnection(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = null; if (_proxy == null) { connection = (HttpURLConnection) url.openConnection(); } else { URLConnection con = url.openConnection(_proxy); String encodedUserPwd = new String(Base64.encodeBase64((_username + ":" + _password).getBytes())); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); connection = (HttpURLConnection) con; } return connection; } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }