label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); try { URL url = new URL("http://placekitten.com/g/500/250"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500); Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); output.eraseColor(Color.BLACK); Canvas canvas = new Canvas(output); canvas.drawBitmap(kitten, 125, 125, new Paint()); canvas.drawBitmap(frame, 0, 0, new Paint()); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); textPaint.setTextAlign(Align.CENTER); textPaint.setAntiAlias(true); textPaint.setTextSize(36); canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint); textPaint.setTextSize(24); canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint); ImageView imageView = (ImageView) this.findViewById(R.id.imageView); imageView.setImageBitmap(output); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected void doGetPost(HttpServletRequest req, HttpServletResponse resp, boolean post) throws ServletException, IOException { if (responseBufferSize > 0) resp.setBufferSize(responseBufferSize); String pathinfo = req.getPathInfo(); if (pathinfo == null) { String urlstring = req.getParameter(REMOTE_URL); if (urlstring == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.nourl")); return; } boolean allowCookieForwarding = "true".equals(req.getParameter(ALLOW_COOKIE_FORWARDING)); boolean allowFormDataForwarding = "true".equals(req.getParameter(ALLOW_FORM_DATA_FORWARDING)); String target = new JGlossURLRewriter(req.getContextPath() + req.getServletPath(), new URL(HttpUtils.getRequestURL(req).toString()), null, allowCookieForwarding, allowFormDataForwarding).rewrite(urlstring, true); resp.sendRedirect(target); return; } Set connectionAllowedProtocols; if (req.isSecure()) connectionAllowedProtocols = secureAllowedProtocols; else connectionAllowedProtocols = allowedProtocols; Object[] oa = JGlossURLRewriter.parseEncodedPath(pathinfo); if (oa == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.malformedrequest"), new Object[] { pathinfo })); return; } boolean allowCookieForwarding = ((Boolean) oa[0]).booleanValue(); boolean allowFormDataForwarding = ((Boolean) oa[1]).booleanValue(); String urlstring = (String) oa[2]; getServletContext().log("received request for " + urlstring); if (urlstring.toLowerCase().indexOf(req.getServletPath().toLowerCase()) != -1) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.addressnotallowed"), new Object[] { urlstring })); return; } if (urlstring.indexOf(':') == -1) { if (req.isSecure()) { if (secureAllowedProtocols.contains("https")) urlstring = "https://" + urlstring; } else { if (allowedProtocols.contains("http")) urlstring = "http://" + urlstring; } } URL url; try { url = new URL(urlstring); } catch (MalformedURLException ex) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.malformedurl"), new Object[] { urlstring })); return; } String protocol = url.getProtocol(); if (!connectionAllowedProtocols.contains(protocol)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.protocolnotallowed"), new Object[] { protocol })); getServletContext().log("protocol not allowed accessing " + url.toString()); return; } boolean remoteIsHttp = protocol.equals("http") || protocol.equals("https"); boolean forwardCookies = remoteIsHttp && enableCookieForwarding && allowCookieForwarding; boolean forwardFormData = remoteIsHttp && enableFormDataForwarding && allowFormDataForwarding && (enableFormDataSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https")); if (forwardFormData) { String query = req.getQueryString(); if (query != null && query.length() > 0) { if (url.getQuery() == null || url.getQuery().length() == 0) url = new URL(url.toExternalForm() + "?" + query); else url = new URL(url.toExternalForm() + "&" + query); } } JGlossURLRewriter rewriter = new JGlossURLRewriter(new URL(req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath() + req.getServletPath()).toExternalForm(), url, connectionAllowedProtocols, allowCookieForwarding, allowFormDataForwarding); URLConnection connection = url.openConnection(); if (forwardFormData && post && remoteIsHttp) { getServletContext().log("using POST"); try { ((HttpURLConnection) connection).setRequestMethod("POST"); } catch (ClassCastException ex) { getServletContext().log("failed to set method POST: " + ex.getMessage()); } connection.setDoInput(true); connection.setDoOutput(true); } String acceptEncoding = buildAcceptEncoding(req.getHeader("accept-encoding")); getServletContext().log("accept-encoding: " + acceptEncoding); if (acceptEncoding != null) connection.setRequestProperty("Accept-Encoding", acceptEncoding); forwardRequestHeaders(connection, req); if (forwardCookies && (enableCookieSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https"))) CookieTools.addRequestCookies(connection, req.getCookies(), getServletContext()); try { connection.connect(); } catch (UnknownHostException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.unknownhost"), new Object[] { url.toExternalForm(), url.getHost() })); return; } catch (IOException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.connect"), new Object[] { url.toExternalForm(), ex.getClass().getName(), ex.getMessage() })); return; } if (forwardFormData && post && remoteIsHttp) { InputStream is = req.getInputStream(); OutputStream os = connection.getOutputStream(); byte[] buf = new byte[512]; int len; while ((len = is.read(buf)) != -1) os.write(buf, 0, len); is.close(); os.close(); } forwardResponseHeaders(connection, req, resp, rewriter); if (forwardCookies && (enableCookieSecureInsecureForwarding || req.isSecure() || !url.getProtocol().equals("https"))) CookieTools.addResponseCookies(connection, resp, req.getServerName(), req.getContextPath() + req.getServletPath(), req.isSecure(), getServletContext()); if (remoteIsHttp) { try { int response = ((HttpURLConnection) connection).getResponseCode(); getServletContext().log("response code " + response); resp.setStatus(response); if (response == 304) return; } catch (ClassCastException ex) { getServletContext().log("failed to read response code: " + ex.getMessage()); } } String type = connection.getContentType(); getServletContext().log("content type " + type + " url " + connection.getURL().toString()); boolean supported = false; if (type != null) { for (int i = 0; i < rewrittenContentTypes.length; i++) if (type.startsWith(rewrittenContentTypes[i])) { supported = true; break; } } if (supported) { String encoding = connection.getContentEncoding(); supported = encoding == null || encoding.endsWith("gzip") || encoding.endsWith("deflate") || encoding.equals("identity"); } if (supported) rewrite(connection, req, resp, rewriter); else tunnel(connection, req, resp); }
11
Code Sample 1: private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; } Code Sample 2: public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&amp;") != -1) { String syn1 = syn.substring(0, syn.indexOf("&amp;")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } }
00
Code Sample 1: public Out(Article article) throws Exception { String body = article.meta(ARTICLE_BODY).getString(); String url = find("a", "href", body); while (url.length() > 0 && url.startsWith("http://")) { System.out.println(url); conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("POST"); int code = conn.getResponseCode(); String ping = conn.getHeaderField("X-Pingback"); System.out.println(ping); if (ping != null) { conn = (HttpURLConnection) new URL(ping).openConnection(); conn.setDoOutput(true); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\"?>\n"); buffer.append("<methodCall>\n"); buffer.append(" <methodName>pingback.ping</methodName>\n"); buffer.append(" <params>\n"); buffer.append(" <param><value><string>http://" + User.host + "/article?id=" + article.getId() + "</string></value></param>\n"); buffer.append(" <param><value><string>" + url + "</string></value></param>\n"); buffer.append(" </params>\n"); buffer.append("</methodCall>\n"); System.out.println(buffer.toString()); OutputStream out = conn.getOutputStream(); out.write(buffer.toString().getBytes("UTF-8")); code = conn.getResponseCode(); InputStream in = null; if (code == 200) { in = conn.getInputStream(); } else if (code < 0) { throw new IOException("HTTP response unreadable."); } else { in = conn.getErrorStream(); } Deploy.pipe(in, System.out); in.close(); } url = find("a", "href", body); } } Code Sample 2: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public void contextInitialized(ServletContextEvent event) { try { String osName = System.getProperty("os.name"); if (osName != null && osName.toLowerCase().contains("windows")) { URL url = new URL("http://localhost/"); URLConnection urlConn = url.openConnection(); urlConn.setDefaultUseCaches(false); } } catch (Throwable t) { } } Code Sample 2: public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); }
11
Code Sample 1: public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } } Code Sample 2: private void copyMerge(Path[] sources, OutputStream out) throws IOException { Configuration conf = getConf(); for (int i = 0; i < sources.length; ++i) { FileSystem fs = sources[i].getFileSystem(conf); InputStream in = fs.open(sources[i]); try { IOUtils.copyBytes(in, out, conf, false); } finally { in.close(); } } }
11
Code Sample 1: public static void nuovoAcquisto(int quantita, Date d, double price, int id) throws SQLException { MyDBConnection c = new MyDBConnection(); c.init(); Connection conn = c.getMyConnection(); PreparedStatement ps = conn.prepareStatement(insertAcquisto); ps.setInt(1, quantita); ps.setDate(2, d); ps.setDouble(3, price); ps.setInt(4, id); ps.executeUpdate(); double newPrice = price; int newQ = quantita; ResultSet rs = MyDBConnection.executeQuery(queryPrezzo.replace("?", "" + id), conn); if (rs.next()) { int oldQ = rs.getInt(1); double oldPrice = rs.getDouble(2); newQ = quantita + oldQ; newPrice = (oldPrice * oldQ + price * quantita) / newQ; updatePortafoglio(conn, newPrice, newQ, id); } else insertPortafoglio(conn, id, newPrice, newQ); try { conn.commit(); } catch (SQLException e) { conn.rollback(); throw new SQLException("Effettuato rollback dopo " + e.getMessage()); } finally { c.close(); } } Code Sample 2: public void updateProfile() throws ClassNotFoundException, SQLException { Connection connection = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(this.url); connection.setAutoCommit(false); String query2 = "UPDATE customers SET password=? WHERE name=?"; String query3 = "UPDATE customers_profile " + "SET first_name=?,middle_name=?,last_name=?,address1=?" + ",address2=?,city=?,post_box=?,email=?,country=? WHERE name=?"; ps1 = connection.prepareStatement(query3); ps2 = connection.prepareStatement(query2); ps1.setString(1, this.firstName); ps1.setString(2, this.middleName); ps1.setString(3, this.lastName); ps1.setString(4, this.address1); ps1.setString(5, this.address2); ps1.setString(6, this.city); ps1.setString(7, this.postBox); ps1.setString(8, this.email); ps1.setString(9, this.country); ps1.setString(10, this.name); ps2.setString(1, this.password); ps2.setString(2, this.name); ps1.executeUpdate(); ps2.executeUpdate(); } catch (Exception ex) { connection.rollback(); } finally { try { this.connection.close(); } catch (Exception ex) { } try { ps1.close(); } catch (Exception ex) { } try { ps2.close(); } catch (Exception ex) { } } }
11
Code Sample 1: public boolean verify(String digest, String password) throws NoSuchAlgorithmException { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{CRYPT}", 0, 7)) { digest = digest.substring(7); return UnixCrypt.matches(digest, password); } else if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } MessageDigest msgDigest = MessageDigest.getInstance(alg); byte[][] hs = split(Base64.decode(digest.toCharArray()), size); byte[] hash = hs[0]; byte[] salt = hs[1]; msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); return msgDigest.isEqual(hash, pwhash); } Code Sample 2: private static String getDigestPassword(String streamId, String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw (RuntimeException) new IllegalStateException().initCause(e); } md.update((streamId + password).getBytes()); byte[] uid = md.digest(); int length = uid.length; StringBuilder digPass = new StringBuilder(); for (int i = 0; i < length; ) { int k = uid[i++]; int iint = k & 0xff; String buf = Integer.toHexString(iint); if (buf.length() == 1) { buf = "0" + buf; } digPass.append(buf); } return digPass.toString(); }
00
Code Sample 1: private void loadInitialDbState() throws IOException { InputStream in = SchemaAndDataPopulator.class.getClassLoader().getResourceAsStream(resourceName); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer); for (String statement : writer.toString().split(SQL_STATEMENT_DELIMITER)) { logger.info("Executing SQL Statement {}", statement); template.execute(statement); } } Code Sample 2: protected PTask commit_result(Result r, SyrupConnection con) throws Exception { try { int logAction = LogEntry.ENDED; String kk = r.context().task().key(); if (r.in_1_consumed() && r.context().in_1_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, false, null, con); logAction = logAction | LogEntry.IN_1; } if (r.in_2_consumed() && r.context().in_2_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, true, null, con); logAction = logAction | LogEntry.IN_2; } if (r.out_1_result() != null && r.context().out_1_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, false, r.out_1_result(), con); logAction = logAction | LogEntry.OUT_1; } if (r.out_2_result() != null && r.context().out_2_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, true, r.out_2_result(), con); logAction = logAction | LogEntry.OUT_2; } sqlImpl().loggingFunctions().log(r.context().task().key(), logAction, con); boolean isParent = r.context().task().isParent(); if (r instanceof Workflow) { Workflow w = (Workflow) r; Task[] tt = w.tasks(); Link[] ll = w.links(); Hashtable tkeyMap = new Hashtable(); for (int i = 0; i < tt.length; i++) { String key = sqlImpl().creationFunctions().newTask(tt[i], r.context().task(), con); tkeyMap.put(tt[i], key); } for (int j = 0; j < ll.length; j++) { sqlImpl().creationFunctions().newLink(ll[j], tkeyMap, con); } String in_link_1 = sqlImpl().queryFunctions().readInTask(kk, false, con); String in_link_2 = sqlImpl().queryFunctions().readInTask(kk, true, con); String out_link_1 = sqlImpl().queryFunctions().readOutTask(kk, false, con); String out_link_2 = sqlImpl().queryFunctions().readOutTask(kk, true, con); sqlImpl().updateFunctions().rewireInLink(kk, false, w.in_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireInLink(kk, true, w.in_2_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, false, w.out_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, true, w.out_2_binding(), tkeyMap, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateDone(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateDone(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_2, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_2, con); isParent = true; } sqlImpl().updateFunctions().checkAndUpdateDone(kk, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kk, con); PreparedStatement s3 = null; s3 = con.prepareStatementFromCache(sqlImpl().sqlStatements().updateTaskModificationStatement()); java.util.Date dd = new java.util.Date(); s3.setLong(1, dd.getTime()); s3.setBoolean(2, isParent); s3.setString(3, r.context().task().key()); s3.executeUpdate(); sqlImpl().loggingFunctions().log(kk, LogEntry.ENDED, con); con.commit(); return sqlImpl().queryFunctions().readPTask(kk, con); } finally { con.rollback(); } }
11
Code Sample 1: public boolean check(Object credentials) { try { byte[] digest = null; if (credentials instanceof Password || credentials instanceof String) { synchronized (__TYPE) { if (__md == null) __md = MessageDigest.getInstance("MD5"); __md.reset(); __md.update(credentials.toString().getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } if (digest == null || digest.length != _digest.length) return false; for (int i = 0; i < digest.length; i++) if (digest[i] != _digest[i]) return false; return true; } else if (credentials instanceof MD5) { MD5 md5 = (MD5) credentials; if (_digest.length != md5._digest.length) return false; for (int i = 0; i < _digest.length; i++) if (_digest[i] != md5._digest[i]) return false; return true; } else if (credentials instanceof Credential) { return ((Credential) credentials).check(this); } else { log.warn("Can't check " + credentials.getClass() + " against MD5"); return false; } } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); return false; } } Code Sample 2: private String getEncryptedPassword() { String encrypted; char[] pwd = password.getPassword(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(new String(pwd).getBytes("UTF-8")); byte[] digested = md.digest(); encrypted = new String(Base64Coder.encode(digested)); } catch (Exception e) { encrypted = new String(pwd); } for (int i = 0; i < pwd.length; i++) pwd[i] = 0; return encrypted; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
00
Code Sample 1: public void getDataFiles(String server, String username, String password, String folder, String destinationFolder) { try { FTPClient ftp = new FTPClient(); ftp.connect(server); ftp.login(username, password); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); ftp.enterLocalActiveMode(); ftp.changeWorkingDirectory(folder); System.out.println("Changed to " + folder); FTPFile[] files = ftp.listFiles(); System.out.println("Number of files in dir: " + files.length); for (int i = 0; i < files.length; i++) { getFiles(ftp, files[i], destinationFolder); } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
11
Code Sample 1: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } } Code Sample 2: private void handleNodeDown(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_NODE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleNodeDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { String ipAddr = activeSvcsRS.getString(1); long serviceID = activeSvcsRS.getLong(2); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleNodeDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleNodeDown: Recording outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID); } catch (SQLException se) { log.warn("Rolling back transaction, nodeDown could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'nodeDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } } Code Sample 2: 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; }
11
Code Sample 1: @Transactional(readOnly = false) public void saveOrUpdateProduct(Product product, File[] doc, String[] docFileName, String[] docContentType) throws IOException { logger.info("addOrUpdateProduct()"); List<Images> imgList = new ArrayList<Images>(); InputStream in = null; OutputStream out = null; String saveDirectory = ServletActionContext.getServletContext().getRealPath("common/userfiles/image/"); if (doc != null && doc.length > 0) { File uploadPath = new File(saveDirectory); if (!uploadPath.exists()) uploadPath.mkdirs(); for (int i = 0; i < doc.length; i++) { Images img = new Images(); in = new FileInputStream(doc[i]); img.setName(docFileName[i].substring(0, docFileName[i].lastIndexOf("."))); img.setRenameAs(docFileName[i]); imgList.add(img); out = new FileOutputStream(saveDirectory + "/" + img.getRenameAs()); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.flush(); } } product.setImagesCollection(imgList); productDao.saveOrUpdateProduct(product); if (null != in) { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != out) { try { out.close(); } catch (Exception e) { logger.info("addOrUpdateProduct() **********" + e.getStackTrace()); e.printStackTrace(); } } } Code Sample 2: String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
11
Code Sample 1: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } }
11
Code Sample 1: private File sendQuery(String query) throws MusicBrainzException { File xmlServerResponse = null; try { xmlServerResponse = new File(SERVER_RESPONSE_FILE); long start = Calendar.getInstance().getTimeInMillis(); System.out.println("\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(" consulta de busqueda -> " + query); URL url = new URL(query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String line = ""; System.out.println(" Respuesta del servidor: \n"); while ((line = in.readLine()) != null) { response += line; } xmlServerResponse = new File(SERVER_RESPONSE_FILE); System.out.println(" Ruta del archivo XML -> " + xmlServerResponse.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(xmlServerResponse)); out.write(response); out.close(); System.out.println("Tamanho del xmlFile -> " + xmlServerResponse.length()); long ahora = (Calendar.getInstance().getTimeInMillis() - start); System.out.println(" Tiempo transcurrido en la consulta (en milesimas) -> " + ahora); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); } catch (IOException e) { e.printStackTrace(); String msg = e.getMessage(); if (e instanceof FileNotFoundException) { msg = "ERROR: MusicBrainz URL used is not found:\n" + msg; } else { } throw new MusicBrainzException(msg); } return xmlServerResponse; } Code Sample 2: private List<String[]> retrieveData(String query) { List<String[]> data = new Vector<String[]>(); query = query.replaceAll("\\s", "+"); String q = "http://www.uniprot.org/uniprot/?query=" + query + "&format=tab&columns=id,protein%20names,organism"; try { URL url = new URL(q); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; reader.readLine(); while ((line = reader.readLine()) != null) { String[] st = line.split("\t"); String[] d = new String[] { st[0], st[1], st[2] }; data.add(d); } reader.close(); if (data.size() == 0) { JOptionPane.showMessageDialog(this, "No data found for query"); } } catch (MalformedURLException e) { System.err.println("Query " + q + " caused exception: "); e.printStackTrace(); } catch (Exception e) { System.err.println("Query " + q + " caused exception: "); e.printStackTrace(); } return data; }
00
Code Sample 1: public static void find(String pckgname, Class<?> tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = tosubclass.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } } Code Sample 2: public static Cursor load(URL url, String descriptor) { if (url == null) { log.log(Level.WARNING, "Trying to load a cursor with a null url."); return null; } String cursorFile = url.getFile(); BufferedReader reader = null; int lineNumber = 0; try { DirectoryTextureLoader loader; URL cursorUrl; if (cursorFile.endsWith(cursorDescriptorFile)) { cursorUrl = url; Cursor cached = cursorCache.get(url); if (cached != null) return cached; reader = new BufferedReader(new InputStreamReader(url.openStream())); loader = new DirectoryTextureLoader(url, false); } else if (cursorFile.endsWith(cursorArchiveFile)) { loader = new DirectoryTextureLoader(url, true); if (descriptor == null) descriptor = defaultDescriptorFile; cursorUrl = loader.makeUrl(descriptor); Cursor cached = cursorCache.get(url); if (cached != null) return cached; ZipInputStream zis = new ZipInputStream(url.openStream()); ZipEntry entry; boolean found = false; while ((entry = zis.getNextEntry()) != null) { if (descriptor.equals(entry.getName())) { found = true; break; } } if (!found) { throw new IOException("Descriptor file \"" + descriptor + "\" was not found."); } reader = new BufferedReader(new InputStreamReader(zis)); } else { log.log(Level.WARNING, "Invalid cursor fileName \"{0}\".", cursorFile); return null; } Cursor cursor = new Cursor(); cursor.url = cursorUrl; List<Integer> delays = new ArrayList<Integer>(); List<String> frameFileNames = new ArrayList<String>(); Map<String, Texture> textureCache = new HashMap<String, Texture>(); String line; while ((line = reader.readLine()) != null) { lineNumber++; int commentIndex = line.indexOf(commentString); if (commentIndex != -1) { line = line.substring(0, commentIndex); } StringTokenizer tokens = new StringTokenizer(line, delims); if (!tokens.hasMoreTokens()) continue; String prefix = tokens.nextToken(); if (prefix.equals(hotSpotXPrefix)) { cursor.hotSpotOffset.x = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(hotSpotYPrefix)) { cursor.hotSpotOffset.y = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(timePrefix)) { delays.add(Integer.valueOf(tokens.nextToken())); if (tokens.nextToken().equals(imagePrefix)) { String file = tokens.nextToken(""); file = file.substring(file.indexOf('=') + 1); file.trim(); frameFileNames.add(file); if (textureCache.get(file) == null) { textureCache.put(file, loader.loadTexture(file)); } } else { throw new NoSuchElementException(); } } } cursor.frameFileNames = frameFileNames.toArray(new String[0]); cursor.textureCache = textureCache; cursor.delays = new int[delays.size()]; cursor.images = new Image[frameFileNames.size()]; cursor.textures = new Texture[frameFileNames.size()]; for (int i = 0; i < cursor.frameFileNames.length; i++) { cursor.textures[i] = textureCache.get(cursor.frameFileNames[i]); cursor.images[i] = cursor.textures[i].getImage(); cursor.delays[i] = delays.get(i); } if (delays.size() == 1) cursor.delays = null; if (cursor.images.length == 0) { log.log(Level.WARNING, "The cursor has no animation frames."); return null; } cursor.width = cursor.images[0].getWidth(); cursor.height = cursor.images[0].getHeight(); cursorCache.put(cursor.url, cursor); return cursor; } catch (MalformedURLException mue) { log.log(Level.WARNING, "Unable to load cursor.", mue); } catch (IOException ioe) { log.log(Level.WARNING, "Unable to load cursor.", ioe); } catch (NumberFormatException nfe) { log.log(Level.WARNING, "Numerical error while parsing the " + "file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (IndexOutOfBoundsException ioobe) { log.log(Level.WARNING, "Error, \"=\" expected in the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (NoSuchElementException nsee) { log.log(Level.WARNING, "Error while parsing the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { log.log(Level.SEVERE, "Unable to close the steam.", ioe); } } } return null; }
00
Code Sample 1: public static String getURLContent(String urlStr) throws MalformedURLException, IOException { URL url = new URL(urlStr); log.info("url: " + url); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer buf = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } in.close(); return buf.toString(); } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
11
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { logger.error(Logger.SECURITY_FAILURE, "Problem decoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public boolean copy(File fromFile) throws IOException { FileUtility toFile = this; if (!fromFile.exists()) { abort("FileUtility: no such source file: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.isFile()) { abort("FileUtility: can't copy directory: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.canRead()) { abort("FileUtility: source file is unreadable: " + fromFile.getAbsolutePath()); return false; } if (this.isDirectory()) toFile = (FileUtility) (new File(this, fromFile.getName())); if (toFile.exists()) { if (!toFile.canWrite()) { abort("FileUtility: destination file is unwriteable: " + pathName); return false; } } else { String parent = toFile.getParent(); File dir = new File(parent); if (!dir.exists()) { abort("FileUtility: destination directory doesn't exist: " + parent); return false; } if (dir.isFile()) { abort("FileUtility: destination is not a directory: " + parent); return false; } if (!dir.canWrite()) { abort("FileUtility: destination directory is unwriteable: " + parent); return false; } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } return true; } Code Sample 2: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } }
11
Code Sample 1: public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } } Code Sample 2: void write() throws IOException { if (!allowUnlimitedArgs && args != null && args.length > 1) throw new IllegalArgumentException("Only one argument allowed unless allowUnlimitedArgs is enabled"); String shebang = "#!" + interpretter; for (int i = 0; i < args.length; i++) { shebang += " " + args[i]; } shebang += '\n'; IOUtils.copy(new StringReader(shebang), outputStream); }
11
Code Sample 1: private static List retrieveQuotes(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; } Code Sample 2: public String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } }
11
Code Sample 1: public static void copyFile(File srcFile, File destFolder) { try { File destFile = new File(destFolder, srcFile.getName()); if (destFile.exists()) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + " as " + destFile + " already exists"); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); destChannel = new FileOutputStream(destFile).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (destChannel != null) { destChannel.close(); } } destFile.setLastModified((srcFile.lastModified())); } catch (IOException e) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + ": " + e, e); } } Code Sample 2: public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } }
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 byte[] sendRequestV1(String url, Map<String, Object> params, String secretCode, String method, Map<String, String> files, String encoding, String signMethod, Map<String, String> headers, String contentType) { HttpClient client = new HttpClient(); byte[] result = null; if (method.equalsIgnoreCase("get")) { GetMethod getMethod = new GetMethod(url); if (contentType == null || contentType.equals("")) getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); else getMethod.setRequestHeader("Content-Type", contentType); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); getMethod.setRequestHeader(key, headers.get(key)); } } try { NameValuePair[] getData; if (params != null) { if (secretCode == null) getData = new NameValuePair[params.size()]; else getData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); getData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature2(params, secretCode, "md5".equalsIgnoreCase(signMethod), isHMac, PARAMETER_SIGN); getData[i] = new NameValuePair(PARAMETER_SIGN, sign); } getMethod.setQueryString(getData); } client.executeMethod(getMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = getMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (bout != null) bout.close(); } } catch (Exception ex) { logger.error(ex, ex); } finally { if (getMethod != null) getMethod.releaseConnection(); } } if (method.equalsIgnoreCase("post")) { PostMethod postMethod = new PostMethod(url); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); postMethod.setRequestHeader(key, headers.get(key)); } } try { if (contentType == null) { if (files != null && files.size() > 0) { Part[] parts; if (secretCode == null) parts = new Part[params.size() + files.size()]; else parts = new Part[params.size() + 1 + files.size()]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); parts[i] = new StringPart(key, params.get(key).toString(), "UTF-8"); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); parts[i] = new StringPart(PARAMETER_SIGN, sign); i++; } iters = files.keySet().iterator(); while (iters.hasNext()) { String key = (String) iters.next(); if (files.get(key).toString().startsWith("http://")) { InputStream bin = null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { URL fileurl = new URL(files.get(key).toString()); bin = fileurl.openStream(); byte[] buf = new byte[500]; int count = 0; while ((count = bin.read(buf)) > 0) { bout.write(buf, 0, count); } parts[i] = new FilePart(key, new ByteArrayPartSource(fileurl.getFile().substring(fileurl.getFile().lastIndexOf("/") + 1), bout.toByteArray())); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bin != null) bin.close(); if (bout != null) bout.close(); } } else parts[i] = new FilePart(key, new File(files.get(key).toString())); i++; } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else { NameValuePair[] postData; if (params != null) { if (secretCode == null) postData = new NameValuePair[params.size()]; else postData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); postData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); postData[i] = new NameValuePair(PARAMETER_SIGN, sign); } postMethod.setRequestBody(postData); } if (contentType == null || contentType.equals("")) postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); } } else { String content = (String) params.get(params.keySet().iterator().next()); RequestEntity entiry = new StringRequestEntity(content, contentType, "UTF-8"); postMethod.setRequestEntity(entiry); } client.executeMethod(postMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = postMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bout != null) bout.close(); } } catch (Exception e) { logger.error(e, e); } finally { if (postMethod != null) postMethod.releaseConnection(); } } return result; }
11
Code Sample 1: public static String encrypt(final String password, final String algorithm, final byte[] salt) { final StringBuffer buffer = new StringBuffer(); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase(algorithm)) { throw new InternalError("Not implemented"); } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append("{SSHA}"); } else { buffer.append("{SHA}"); } try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append("{SMD5}"); } else { buffer.append("{MD5}"); } try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } int outSize = size; digest.reset(); digest.update(password.getBytes()); if (salt != null && salt.length > 0) { digest.update(salt); outSize += salt.length; } final byte[] out = new byte[outSize]; System.arraycopy(digest.digest(), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy(salt, 0, out, size, salt.length); } buffer.append(Base64.encode(out)); return buffer.toString(); } Code Sample 2: private String buildShaHashOf(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(source.getBytes()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static byte[] hash(String plainTextValue) { MessageDigest msgDigest; try { msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(plainTextValue.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); return digest; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } }
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.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
00
Code Sample 1: public static String callApi(String api, String paramname, String paramvalue) { String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/" + api, paramname, paramvalue); u = SSOUtil.addParameter(u, "servicekey", SSOFilter.getServicekey()); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } } Code Sample 2: @Override @SuppressWarnings("empty-statement") public void run() { String server = System.getProperty("server.downsampler"); if (server == null) server = FALLBACK; String url = server + "cgi-bin/downsample.cgi?" + this._uri.toString(); url = url.replaceAll("\\?#$", ""); try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoInput(true); this._input_stream = connection.getInputStream(); while (this._input_stream.read() != '\n') ; this._complete = true; } catch (Exception e) { new ErrorEvent().send(e); } }
11
Code Sample 1: 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()); } } Code Sample 2: public Reader transform(Reader reader, Map<String, Object> parameterMap) { try { File file = File.createTempFile("srx2", ".srx"); file.deleteOnExit(); Writer writer = getWriter(getFileOutputStream(file.getAbsolutePath())); transform(reader, writer, parameterMap); writer.close(); Reader resultReader = getReader(getFileInputStream(file.getAbsolutePath())); return resultReader; } catch (IOException e) { throw new IORuntimeException(e); } }
11
Code Sample 1: public Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; } Code Sample 2: public static void copyFile(String src, String target) throws IOException { FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(target).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
00
Code Sample 1: @org.junit.Test public void simpleRead() throws Exception { final InputStream istream = StatsInputStreamTest.class.getResourceAsStream("/testFile.txt"); final StatsInputStream ris = new StatsInputStream(istream); assertEquals("read size", 0, ris.getSize()); IOUtils.copy(ris, new NullOutputStream()); assertEquals("in the end", 30, ris.getSize()); } Code Sample 2: private void loadOverrideProperties(String uri) { try { File f = new File(uri); Properties temp = new Properties(); if (f.exists()) { info("Found config override file " + f.getAbsolutePath()); try { InputStream readStream = new BufferedInputStream(new FileInputStream(f)); try { temp.load(readStream); } finally { readStream.close(); } } catch (IOException iex) { warning("Error while loading override properties file; skipping.", iex); return; } } else { InputStream in = null; try { URL url = new URL(uri); in = new BufferedInputStream(url.openStream()); info("Found config override URI " + uri); temp.load(in); } catch (MalformedURLException e) { warning("URI for override properties is malformed, skipping: " + uri); return; } catch (IOException e) { warning("Overridden properties could not be loaded from URI: " + uri, e); return; } finally { if (in != null) try { in.close(); } catch (IOException e) { } } } Enumeration elem = this.properties.keys(); List lp = Collections.list(elem); Collections.sort(lp); Iterator iter = lp.iterator(); int cnt = 0; while (iter.hasNext()) { String key = (String) iter.next(); String val = temp.getProperty(key); if (val != null) { this.properties.setProperty(key, val); finer(" " + key + " -> " + val); cnt++; } } finer("Configuration: " + cnt + " properties overridden from secondary properties file."); Enumeration allRead = temp.keys(); List ap = Collections.list(allRead); Collections.sort(ap); iter = ap.iterator(); cnt = 0; while (iter.hasNext()) { String key = (String) iter.next(); String val = temp.getProperty(key); if (val != null) { this.properties.setProperty(key, val); finer(" (+)" + key + " -> " + val); cnt++; } } finer("Configuration: " + cnt + " properties added from secondary properties file."); } catch (SecurityException e) { System.err.println(e.getLocalizedMessage()); } }
00
Code Sample 1: public static String executePost(String urlStr, String content) { StringBuffer result = new StringBuffer(); try { Authentication.doIt(); URL url = new URL(urlStr); System.out.println("Host: " + url.getHost()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); System.out.println("got connection "); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + content.length()); connection.setRequestProperty("SOAPAction", "\"http://niki-bt.act.cmis.csiro.org/SMSService/SendText\""); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print(content); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String msg = result.toString(); if (msg != null) { int beginCut = msg.indexOf('>'); int endCut = msg.lastIndexOf('<'); if (beginCut != -1 && endCut != -1) { return msg.substring(beginCut + 1, endCut); } } return null; } Code Sample 2: public List<String> loadList(String name) { List<String> ret = new ArrayList<String>(); try { URL url = getClass().getClassLoader().getResource("lists/" + name + ".utf-8"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { ret.add(line); } reader.close(); } catch (IOException e) { showError("No se puede cargar la lista de valores: " + name, e); } return ret; }
11
Code Sample 1: public void process(String t) { try { MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST); md5.reset(); md5.update(t.getBytes()); callback.display(null, digestToHexString(md5.digest())); } catch (Exception ex) { callback.display(null, "[failed]"); } } Code Sample 2: public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static String readFromURL(String url_) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(url_); System.setProperty("http.agent", ""); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); connection.setDoInput(true); InputStream inStream = connection.getInputStream(); BufferedReader input = new BufferedReader(new InputStreamReader(inStream, "utf8")); String line = ""; while ((line = input.readLine()) != null) { buffer.append(line + "\n"); } } catch (Exception e) { System.out.println(e.toString()); } return buffer.toString(); } Code Sample 2: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public boolean update(int idPartida, partida partidaModificada) { int intResult = 0; String sql = "UPDATE partida " + "SET torneo_idTorneo = ?, " + " jugador_idJugadorNegras = ?, jugador_idJugadorBlancas = ?, " + " fecha = ?, " + " resultado = ?, " + " nombreBlancas = ?, nombreNegras = ?, eloBlancas = ?, eloNegras = ?, idApertura = ? " + " WHERE idPartida = " + idPartida; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement2(partidaModificada); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: private void copyJdbcDriverToWL(final WLPropertyPage page) { final File url = new File(page.getDomainDirectory()); final File lib = new File(url, "lib"); final File mysqlLibrary = new File(lib, NexOpenUIActivator.getDefault().getMySQLDriver()); if (!mysqlLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + NexOpenUIActivator.getDefault().getMySQLDriver())); fos = new FileOutputStream(mysqlLibrary); IOUtils.copy(driver, fos); } catch (final IOException e) { Logger.log(Logger.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); final Status status = new Status(Status.ERROR, NexOpenUIActivator.PLUGIN_ID, Status.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); ErrorDialog.openError(page.getShell(), "Bea WebLogic MSQL support", "Could not copy the MySQL Driver jar file to Bea WL", status); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } Code Sample 2: public static String downloadWebpage1(String address) throws MalformedURLException, IOException { URL url = new URL(address); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
11
Code Sample 1: private static boolean moveFiles(String sourceDir, String targetDir) { boolean isFinished = false; boolean fileMoved = false; File stagingDir = new File(sourceDir); if (!stagingDir.exists()) { System.out.println(getTimeStamp() + "ERROR - source directory does not exist."); return true; } if (stagingDir.listFiles() == null) { System.out.println(getTimeStamp() + "ERROR - Empty file list. Possible permission error on source directory " + sourceDir); return true; } File[] fileList = stagingDir.listFiles(); for (int x = 0; x < fileList.length; x++) { File f = fileList[x]; if (f.getName().startsWith(".")) { continue; } String targetFileName = targetDir + File.separator + f.getName(); String operation = "move"; boolean success = f.renameTo(new File(targetFileName)); if (success) { fileMoved = true; } else { operation = "mv"; try { Process process = Runtime.getRuntime().exec(new String[] { "mv", f.getCanonicalPath(), targetFileName }); process.waitFor(); process.destroy(); if (!new File(targetFileName).exists()) { success = false; } else { success = true; fileMoved = true; } } catch (Exception e) { success = false; } if (!success) { operation = "copy"; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(f).getChannel(); File outFile = new File(targetFileName); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); in = null; out.close(); out = null; f.delete(); success = true; } catch (Exception e) { success = false; } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } } } } if (success) { System.out.println(getTimeStamp() + operation + " " + f.getAbsolutePath() + " to " + targetDir); fileMoved = true; } else { System.out.println(getTimeStamp() + "ERROR - " + operation + " " + f.getName() + " to " + targetFileName + " failed."); isFinished = true; } } if (fileMoved && !isFinished) { try { currentLastActivity = System.currentTimeMillis(); updateLastActivity(currentLastActivity); } catch (NumberFormatException e) { System.out.println(getTimeStamp() + "ERROR: NumberFormatException when trying to update lastActivity."); isFinished = true; } catch (IOException e) { System.out.println(getTimeStamp() + "ERROR: IOException when trying to update lastActivity. " + e.toString()); isFinished = true; } } return isFinished; } Code Sample 2: public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } }
00
Code Sample 1: public String report() { if (true) return "-"; StringBuffer parameter = new StringBuffer("?"); if (getRecord_ID() == 0) return "ID=0"; if (getRecord_ID() == 1) { parameter.append("ISSUE="); HashMap htOut = get_HashMap(); try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutput oOut = new ObjectOutputStream(bOut); oOut.writeObject(htOut); oOut.flush(); String hexString = Secure.convertToHexString(bOut.toByteArray()); parameter.append(hexString); } catch (Exception e) { log.severe(e.getLocalizedMessage()); return "New-" + e.getLocalizedMessage(); } } else { try { parameter.append("RECORDID=").append(getRecord_ID()); parameter.append("&DBADDRESS=").append(URLEncoder.encode(getDBAddress(), "UTF-8")); parameter.append("&COMMENTS=").append(URLEncoder.encode(getComments(), "UTF-8")); } catch (Exception e) { log.severe(e.getLocalizedMessage()); return "Update-" + e.getLocalizedMessage(); } } InputStreamReader in = null; String target = "http://dev1/wstore/issueReportServlet"; try { StringBuffer urlString = new StringBuffer(target).append(parameter); URL url = new URL(urlString.toString()); URLConnection uc = url.openConnection(); in = new InputStreamReader(uc.getInputStream()); } catch (Exception e) { String msg = "Cannot connect to http://" + target; if (e instanceof FileNotFoundException || e instanceof ConnectException) msg += "\nServer temporarily down - Please try again later"; else { msg += "\nCheck connection - " + e.getLocalizedMessage(); log.log(Level.FINE, msg); } return msg; } return readResponse(in); } Code Sample 2: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); }
11
Code Sample 1: private static void unpackEntry(File destinationFile, ZipInputStream zin, ZipEntry entry) throws Exception { if (!entry.isDirectory()) { createFolders(destinationFile.getParentFile()); FileOutputStream fis = new FileOutputStream(destinationFile); try { IOUtils.copy(zin, fis); } finally { zin.closeEntry(); fis.close(); } } else { createFolders(destinationFile); } } Code Sample 2: public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
00
Code Sample 1: public void loginSendSpace() throws Exception { loginsuccessful = false; HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to sendspace"); HttpPost httppost = new HttpPost("http://www.sendspace.com/login.html"); httppost.setHeader("Cookie", sidcookie + ";" + ssuicookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("submit", "login")); formparams.add(new BasicNameValuePair("target", "%252F")); formparams.add(new BasicNameValuePair("action_type", "login")); formparams.add(new BasicNameValuePair("remember", "1")); formparams.add(new BasicNameValuePair("username", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("ssal")) { ssalcookie = escookie.getName() + "=" + escookie.getValue(); NULogger.getLogger().info(ssalcookie); loginsuccessful = true; } } if (loginsuccessful) { username = getUsername(); password = getPassword(); NULogger.getLogger().info("SendSpace login success :)"); } else { NULogger.getLogger().info("SendSpace login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } } Code Sample 2: private Scanner getUrlScanner(String strUrl) { URL urlParticipants = null; Scanner scannerParticipants; try { urlParticipants = new URL(strUrl); URLConnection connParticipants; if (StringUtils.isBlank(this.configProxyIp)) { connParticipants = urlParticipants.openConnection(); } else { SocketAddress address = new InetSocketAddress(this.configProxyIp, this.configProxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connParticipants = urlParticipants.openConnection(proxy); } InputStream streamParticipant = connParticipants.getInputStream(); String charSet = StringUtils.substringAfterLast(connParticipants.getContentType(), "charset="); scannerParticipants = new Scanner(streamParticipant, charSet); } catch (MalformedURLException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "MalformedURLException"), new Object[] { urlParticipants.toString() })); } catch (IOException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "IOException"), new Object[] { urlParticipants.toString() })); } return scannerParticipants; }
00
Code Sample 1: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); } Code Sample 2: private boolean cacheUrlFile(String filePath, String realUrl, boolean isOnline) { try { URL url = new URL(realUrl); String encoding = "gbk"; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), encoding)); StringBuilder sb = new StringBuilder(); sb.append(configCenter.getWebRoot()).append(getCacheString(isOnline)).append(filePath); fileEditor.createDirectory(sb.toString()); return fileEditor.saveFile(sb.toString(), in); } catch (IOException e) { } return false; }
00
Code Sample 1: public Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } } Code Sample 2: public void testGet() throws Exception { HttpGet request = new HttpGet(baseUri + "/test"); HttpResponse response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public SqlScript(URL url, IDbDialect platform, boolean failOnError, String delimiter, Map<String, String> replacementTokens) { try { fileName = url.getFile(); fileName = fileName.substring(fileName.lastIndexOf("/") + 1); log.log(LogLevel.INFO, "Loading sql from script %s", fileName); init(IoUtils.readLines(new InputStreamReader(url.openStream(), "UTF-8")), platform, failOnError, delimiter, replacementTokens); } catch (IOException ex) { log.error(ex); throw new RuntimeException(ex); } }
00
Code Sample 1: public static String calculateHash(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.reset(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(password.getBytes()); return byteToBase64(md.digest()); } Code Sample 2: public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } } Code Sample 2: private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); WebResponse response = wc.getResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
11
Code Sample 1: private static void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name + "/"); zip.putNextEntry(zipEntry); zip.closeEntry(); addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(updateFilename(name)); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } } Code Sample 2: private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), e); } }
11
Code Sample 1: public String sendRequestHTTPTunelling(java.lang.String servletName, java.lang.String request) { String reqxml = ""; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); String req1xml = request; java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println(req1xml); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("log.txt"); pw.write(req1xml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8"); retdoc = (new org.jdom.input.SAXBuilder()).build(br); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("log3.txt"); pw.write(reqxml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(System.out); javax.swing.JOptionPane.showMessageDialog(null, "<html>Could not establish connection with the server, <br>Please verify server name/IP adress, <br>Also check if NewGenLib server is running</html>", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE); } System.out.println(reqxml); return (new org.jdom.output.XMLOutputter()).outputString(retdoc); } Code Sample 2: public static List<String> list() throws IOException { List<String> providers = new ArrayList<String>(); Enumeration<URL> urls = ClassLoader.getSystemResources("sentrick.classifiers"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); String provider = null; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((provider = in.readLine()) != null) { provider = provider.trim(); if (provider.length() > 0) providers.add(provider); } in.close(); } return providers; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private byte[] hash(String data, HashAlg alg) { try { MessageDigest digest = MessageDigest.getInstance(alg.toString()); digest.update(data.getBytes()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { } return null; }
00
Code Sample 1: public String parse(String term) throws OntologyAdaptorException { try { String sUrl = getUrl(term); if (sUrl.length() > 0) { URL url = new URL(sUrl); InputStream in = url.openStream(); StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = r.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } return sb.toString(); } else { return ""; } } catch (Exception ex) { throw new OntologyAdaptorException("Convertion to lucene failed.", ex); } } Code Sample 2: public SukuData updatePerson(String usertext, SukuData req) { String insPers; String userid = Utils.toUsAscii(usertext); if (userid != null && userid.length() > 16) { userid = userid.substring(0, 16); } StringBuilder sb = new StringBuilder(); sb.append("insert into unit (pid,tag,privacy,groupid,sex,sourcetext,privatetext,userrefn"); if (userid != null) { sb.append(",createdby"); } sb.append(") values (?,?,?,?,?,?,?,? "); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insPers = sb.toString(); String updPers; sb = new StringBuilder(); sb.append("update unit set privacy=?,groupid=?,sex=?,sourcetext=?," + "privatetext=?,userrefn=?,Modified=now()"); if (userid != null) { sb.append(",modifiedby = '" + userid + "' where pid = ?"); } else { sb.append(" where pid = ?"); } updPers = sb.toString(); sb = new StringBuilder(); String updSql; sb.append("update unitnotice set "); sb.append("surety=?,Privacy=?,NoticeType=?,Description=?,"); sb.append("DatePrefix=?,FromDate=?,ToDate=?,Place=?,"); sb.append("Village=?,Farm=?,Croft=?,Address=?,"); sb.append("PostalCode=?,PostOffice=?,State=?,Country=?,Email=?,"); sb.append("NoteText=?,MediaFilename=?,MediaTitle=?,Prefix=?,"); sb.append("Surname=?,Givenname=?,Patronym=?,PostFix=?,"); sb.append("SourceText=?,PrivateText=?,RefNames=?,RefPlaces=?,Modified=now()"); if (userid != null) { sb.append(",modifiedby = '" + userid + "'"); } sb.append(" where pnid = ?"); updSql = sb.toString(); sb = new StringBuilder(); String insSql; sb.append("insert into unitnotice ("); sb.append("surety,Privacy,NoticeType,Description,"); sb.append("DatePrefix,FromDate,ToDate,Place,"); sb.append("Village,Farm,Croft,Address,"); sb.append("PostalCode,PostOffice,State,Country,Email,"); sb.append("NoteText,MediaFilename,MediaTitle,Prefix,"); sb.append("Surname,Givenname,Patronym,PostFix,"); sb.append("SourceText,PrivateText,RefNames,Refplaces,pnid,pid,tag"); if (userid != null) { sb.append(",createdby"); } sb.append(") values ("); sb.append("?,?,?,?,?,?,?,?," + "?,?,?,?,?,?,?,?," + "?,?,?,?,?,?,?,?,"); sb.append("?,?,?,?,?,?,?,?"); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insSql = sb.toString(); sb = new StringBuilder(); String updLangSql; sb.append("update unitlanguage set "); sb.append("NoticeType=?,Description=?," + "Place=?,"); sb.append("NoteText=?,MediaTitle=?,Modified=now() "); if (userid != null) { sb.append(",modifiedby = '" + userid + "'"); } sb.append("where pnid=? and langCode = ?"); updLangSql = sb.toString(); sb = new StringBuilder(); String insLangSql; sb.append("insert into unitlanguage (pnid,pid,tag,langcode,"); sb.append("NoticeType,Description,Place,"); sb.append("NoteText,MediaTitle"); if (userid != null) { sb.append(",createdby"); } sb.append(") values (?,?,?,?,?,?,?,?,?"); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insLangSql = sb.toString(); String delOneLangSql = "delete from unitlanguage where pnid = ? and langcode = ? "; String updRowSql = "update unitnotice set noticerow = ? where pnid = ? "; String delSql = "delete from unitnotice where pnid = ? "; String delAllLangSql = "delete from Unitlanguage where pnid = ? "; SukuData res = new SukuData(); UnitNotice[] nn = req.persLong.getNotices(); if (nn != null) { String prevName = ""; String prevOccu = ""; for (int i = 0; i < nn.length; i++) { if (nn[i].getTag().equals("NAME")) { String thisName = Utils.nv(nn[i].getGivenname()) + "/" + Utils.nv(nn[i].getPatronym()) + "/" + Utils.nv(nn[i].getPrefix()) + "/" + Utils.nv(nn[i].getSurname()) + "/" + Utils.nv(nn[i].getPostfix()); if (thisName.equals(prevName) && !prevName.equals("")) { if (nn[i].isToBeDeleted() == false) { String e = Resurses.getString("IDENTICAL_NAMES_ERROR") + " [" + req.persLong.getPid() + "] idx [" + i + "] = " + thisName; logger.warning(e); if (req.persLong.getPid() > 0) { res.resu = e; return res; } } } prevName = thisName; } else if (nn[i].getTag().equals("OCCU")) { String thisOccu = Utils.nv(nn[i].getDescription()); if (thisOccu.equals(prevOccu) && !prevOccu.equals("")) { if (nn[i].isToBeDeleted() == false) { String e = Resurses.getString("IDENTICAL_OCCU_ERROR") + " [" + req.persLong.getPid() + "] idx [" + i + "] = '" + thisOccu + "'"; logger.warning(e); if (req.persLong.getPid() > 0) { res.resu = e; return res; } } } prevOccu = thisOccu; } } } int pid = 0; try { con.setAutoCommit(false); Statement stm; PreparedStatement pst; if (req.persLong.getPid() > 0) { res.resultPid = req.persLong.getPid(); pid = req.persLong.getPid(); if (req.persLong.isMainModified()) { if (req.persLong.getModified() == null) { pst = con.prepareStatement(updPers + " and modified is null "); } else { pst = con.prepareStatement(updPers + " and modified = ?"); } pst.setString(1, req.persLong.getPrivacy()); pst.setString(2, req.persLong.getGroupId()); pst.setString(3, req.persLong.getSex()); pst.setString(4, req.persLong.getSource()); pst.setString(5, req.persLong.getPrivateText()); pst.setString(6, req.persLong.getRefn()); pst.setInt(7, req.persLong.getPid()); if (req.persLong.getModified() != null) { pst.setTimestamp(8, req.persLong.getModified()); } int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("Person update for pid " + pid + " failed [" + lukuri + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_1"); } String apara = null; String bpara = null; String cpara = null; String dpara = null; if (req.persLong.getSex().equals("M")) { apara = "FATH"; bpara = "MOTH"; cpara = "HUSB"; dpara = "WIFE"; } else if (req.persLong.getSex().equals("F")) { bpara = "FATH"; apara = "MOTH"; dpara = "HUSB"; cpara = "WIFE"; } if (apara != null) { String sqlParent = "update relation as b set tag=? " + "where b.rid in (select a.rid from relation as a " + "where a.pid = ? and a.pid <> b.rid and a.tag='CHIL') " + "and tag=?"; PreparedStatement ppare = con.prepareStatement(sqlParent); ppare.setString(1, apara); ppare.setInt(2, req.persLong.getPid()); ppare.setString(3, bpara); int resup = ppare.executeUpdate(); logger.fine("updated count for person parent= " + resup); String sqlSpouse = "update relation as b set tag=? " + "where b.rid in (select a.rid " + "from relation as a where a.pid = ? and a.pid <> b.pid " + "and a.tag in ('HUSB','WIFE')) and tag=?"; ppare = con.prepareStatement(sqlSpouse); ppare.setString(1, cpara); ppare.setInt(2, req.persLong.getPid()); ppare.setString(3, dpara); resup = ppare.executeUpdate(); logger.fine("updated count for person spouse= " + resup); } } } else { stm = con.createStatement(); ResultSet rs = stm.executeQuery("select nextval('unitseq')"); if (rs.next()) { pid = rs.getInt(1); res.resultPid = pid; } else { throw new SQLException("Sequence unitseq error"); } rs.close(); pst = con.prepareStatement(insPers); pst.setInt(1, pid); pst.setString(2, req.persLong.getTag()); pst.setString(3, req.persLong.getPrivacy()); pst.setString(4, req.persLong.getGroupId()); pst.setString(5, req.persLong.getSex()); pst.setString(6, req.persLong.getSource()); pst.setString(7, req.persLong.getPrivateText()); pst.setString(8, req.persLong.getRefn()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("Person created for pid " + pid + " gave result " + lukuri); } } PreparedStatement pstDel = con.prepareStatement(delSql); PreparedStatement pstDelLang = con.prepareStatement(delAllLangSql); PreparedStatement pstUpdRow = con.prepareStatement(updRowSql); if (nn != null) { for (int i = 0; i < nn.length; i++) { UnitNotice n = nn[i]; int pnid = 0; if (n.isToBeDeleted()) { pstDelLang.setInt(1, n.getPnid()); int landelcnt = pstDelLang.executeUpdate(); pstDel.setInt(1, n.getPnid()); int delcnt = pstDel.executeUpdate(); if (delcnt != 1) { logger.warning("Person notice [" + n.getTag() + "]delete for pid " + pid + " failed [" + delcnt + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_2"); } String text = "Poistettiin " + delcnt + " riviä [" + landelcnt + "] kieliversiota pid = " + n.getPid() + " tag=" + n.getTag(); logger.fine(text); } else if (n.getPnid() == 0 || n.isToBeUpdated()) { if (n.getPnid() == 0) { stm = con.createStatement(); ResultSet rs = stm.executeQuery("select nextval('unitnoticeseq')"); if (rs.next()) { pnid = rs.getInt(1); } else { throw new SQLException("Sequence unitnoticeseq error"); } rs.close(); pst = con.prepareStatement(insSql); } else { if (n.getModified() == null) { pst = con.prepareStatement(updSql + " and modified is null "); } else { pst = con.prepareStatement(updSql + " and modified = ?"); } pnid = n.getPnid(); } if (n.isToBeUpdated() || n.getPnid() == 0) { pst.setInt(1, n.getSurety()); pst.setString(2, n.getPrivacy()); pst.setString(3, n.getNoticeType()); pst.setString(4, n.getDescription()); pst.setString(5, n.getDatePrefix()); pst.setString(6, n.getFromDate()); pst.setString(7, n.getToDate()); pst.setString(8, n.getPlace()); pst.setString(9, n.getVillage()); pst.setString(10, n.getFarm()); pst.setString(11, n.getCroft()); pst.setString(12, n.getAddress()); pst.setString(13, n.getPostalCode()); pst.setString(14, n.getPostOffice()); pst.setString(15, n.getState()); pst.setString(16, n.getCountry()); pst.setString(17, n.getEmail()); pst.setString(18, n.getNoteText()); pst.setString(19, n.getMediaFilename()); pst.setString(20, n.getMediaTitle()); pst.setString(21, n.getPrefix()); pst.setString(22, n.getSurname()); pst.setString(23, n.getGivenname()); pst.setString(24, n.getPatronym()); pst.setString(25, n.getPostfix()); pst.setString(26, n.getSource()); pst.setString(27, n.getPrivateText()); if (n.getRefNames() == null) { pst.setNull(28, Types.ARRAY); } else { Array xx = con.createArrayOf("varchar", n.getRefNames()); pst.setArray(28, xx); } if (n.getRefPlaces() == null) { pst.setNull(29, Types.ARRAY); } else { Array xx = con.createArrayOf("varchar", n.getRefPlaces()); pst.setArray(29, xx); } } if (n.getPnid() > 0) { pst.setInt(30, n.getPnid()); if (n.getModified() != null) { pst.setTimestamp(31, n.getModified()); } int luku = pst.executeUpdate(); if (luku != 1) { logger.warning("Person notice [" + n.getTag() + "] update for pid " + pid + " failed [" + luku + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_3"); } logger.fine("Päivitettiin " + luku + " tietuetta pnid=[" + n.getPnid() + "]"); } else { pst.setInt(30, pnid); pst.setInt(31, pid); pst.setString(32, n.getTag()); int luku = pst.executeUpdate(); logger.fine("Luotiin " + luku + " tietue pnid=[" + pnid + "]"); } if (n.getMediaData() == null) { String sql = "update unitnotice set mediadata = null where pnid = ?"; pst = con.prepareStatement(sql); pst.setInt(1, pnid); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("media deleted for pnid " + n.getPnid() + " gave result " + lukuri); } } else { String UPDATE_IMAGE_DATA = "update UnitNotice set MediaData = ?," + "mediaWidth = ?,mediaheight = ? where PNID = ? "; PreparedStatement ps = this.con.prepareStatement(UPDATE_IMAGE_DATA); ps.setBytes(1, n.getMediaData()); Dimension d = n.getMediaSize(); ps.setInt(2, d.width); ps.setInt(3, d.height); ps.setInt(4, pnid); ps.executeUpdate(); } } if (n.getLanguages() != null) { for (int l = 0; l < n.getLanguages().length; l++) { UnitLanguage ll = n.getLanguages()[l]; if (ll.isToBeDeleted()) { if (ll.getPnid() > 0) { pst = con.prepareStatement(delOneLangSql); pst.setInt(1, ll.getPnid()); pst.setString(2, ll.getLangCode()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language deleted for pnid " + n.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } } } if (ll.isToBeUpdated()) { if (ll.getPnid() == 0) { pst = con.prepareStatement(insLangSql); pst.setInt(1, n.getPnid()); pst.setInt(2, pid); pst.setString(3, n.getTag()); pst.setString(4, ll.getLangCode()); pst.setString(5, ll.getNoticeType()); pst.setString(6, ll.getDescription()); pst.setString(7, ll.getPlace()); pst.setString(8, ll.getNoteText()); pst.setString(9, ll.getMediaTitle()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language added for pnid " + n.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } } else { pst = con.prepareStatement(updLangSql); pst.setString(1, ll.getNoticeType()); pst.setString(2, ll.getDescription()); pst.setString(3, ll.getPlace()); pst.setString(4, ll.getNoteText()); pst.setString(5, ll.getMediaTitle()); pst.setInt(6, ll.getPnid()); pst.setString(7, ll.getLangCode()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language for pnid " + ll.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } pst.close(); } } } } if (n.getPnid() > 0) { pnid = n.getPnid(); } pstUpdRow.setInt(1, i + 1); pstUpdRow.setInt(2, pnid); pstUpdRow.executeUpdate(); } } if (req.relations != null) { if (req.persLong.getPid() == 0) { req.persLong.setPid(pid); for (int i = 0; i < req.relations.length; i++) { Relation r = req.relations[i]; if (r.getPid() == 0) { r.setPid(pid); } } } updateRelations(userid, req); } con.commit(); } catch (Exception e) { try { con.rollback(); } catch (SQLException e1) { logger.log(Level.WARNING, "Person update rollback failed", e1); } logger.log(Level.WARNING, "person update rolled back for [" + pid + "]", e); res.resu = e.getMessage(); return res; } finally { try { con.setAutoCommit(true); } catch (SQLException e) { logger.log(Level.WARNING, "set autocommit failed", e); } } return res; }
11
Code Sample 1: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static String generateHash(String msg) throws NoSuchAlgorithmException { if (msg == null) { throw new IllegalArgumentException("Input string can not be null"); } MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(msg.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); String hashText = bigInt.toString(16); while (hashText.length() < 32) { hashText = "0" + hashText; } return hashText; } Code Sample 2: public static String validateAuthTicketAndGetSessionId(ServletRequest request, String servicekey) { String loginapp = SSOFilter.getLoginapp(); String authticket = request.getParameter("authticket"); String u = SSOUtil.addParameter(loginapp + "/api/validateauthticket", "authticket", authticket); u = SSOUtil.addParameter(u, "servicekey", servicekey); String sessionid = null; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { sessionid = line.trim(); } reader.close(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } if ("error".equals(sessionid)) { return null; } return sessionid; }
11
Code Sample 1: public void testStorageStringWriter() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { Writer w = r.getWriter(); w.write("This is an example"); w.write(" and another one."); w.flush(); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } try { r.getOutputStream(); fail("Is not allowed as you already called getWriter()."); } catch (IOException e) { } { Writer output = r.getWriter(); output.write(" and another line"); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and some more."); assertEquals("This is an example and another one. and another line and write some more and some more.", r.getText()); } r.setEndState(ResponseStateOk.getInstance()); assertEquals(ResponseStateOk.getInstance(), r.getEndState()); try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } } Code Sample 2: private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: public static void copyFile(File src, File dest) { try { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.err.println(ioe); } }
11
Code Sample 1: private String xifraPassword() throws Exception { String password2 = instance.getUsuaris().getPassword2(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(password2.getBytes(), 0, password2.length()); password2 = new BigInteger(1, m.digest()).toString(16); return password2; } Code Sample 2: public static String md5Crypt(final byte[] key, final byte[] salt) throws NoSuchAlgorithmException { if (key == null || key.length == 0) { throw new IllegalArgumentException("Argument 'key' cannot be null or an empty array."); } if (salt == null || salt.length == 0) { throw new IllegalArgumentException("Argument 'salt' cannot be null or an empty array."); } final MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(key); _md.update(MAGIC.getBytes()); _md.update(salt); final MessageDigest md2 = MessageDigest.getInstance("MD5"); md2.update(key); md2.update(salt); md2.update(key); byte[] abyFinal = md2.digest(); for (int n = key.length; n > 0; n -= 16) { _md.update(abyFinal, 0, n > 16 ? 16 : n); } abyFinal = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int j = 0, i = key.length; i != 0; i >>>= 1) { if ((i & 1) == 1) _md.update(abyFinal, j, 1); else _md.update(key, j, 1); } final StringBuilder sbPasswd = new StringBuilder(); sbPasswd.append(MAGIC); sbPasswd.append(new String(salt)); sbPasswd.append('$'); abyFinal = _md.digest(); for (int n = 0; n < 1000; n++) { final MessageDigest md3 = MessageDigest.getInstance("MD5"); if ((n & 1) != 0) { md3.update(key); } else { md3.update(abyFinal); } if ((n % 3) != 0) { md3.update(salt); } if ((n % 7) != 0) { md3.update(key); } if ((n & 1) != 0) { md3.update(abyFinal); } else { md3.update(key); } abyFinal = md3.digest(); } int[] anFinal = new int[] { (abyFinal[0] & 0x7f) | (abyFinal[0] & 0x80), (abyFinal[1] & 0x7f) | (abyFinal[1] & 0x80), (abyFinal[2] & 0x7f) | (abyFinal[2] & 0x80), (abyFinal[3] & 0x7f) | (abyFinal[3] & 0x80), (abyFinal[4] & 0x7f) | (abyFinal[4] & 0x80), (abyFinal[5] & 0x7f) | (abyFinal[5] & 0x80), (abyFinal[6] & 0x7f) | (abyFinal[6] & 0x80), (abyFinal[7] & 0x7f) | (abyFinal[7] & 0x80), (abyFinal[8] & 0x7f) | (abyFinal[8] & 0x80), (abyFinal[9] & 0x7f) | (abyFinal[9] & 0x80), (abyFinal[10] & 0x7f) | (abyFinal[10] & 0x80), (abyFinal[11] & 0x7f) | (abyFinal[11] & 0x80), (abyFinal[12] & 0x7f) | (abyFinal[12] & 0x80), (abyFinal[13] & 0x7f) | (abyFinal[13] & 0x80), (abyFinal[14] & 0x7f) | (abyFinal[14] & 0x80), (abyFinal[15] & 0x7f) | (abyFinal[15] & 0x80) }; to64(sbPasswd, anFinal[0] << 16 | anFinal[6] << 8 | anFinal[12], 4); to64(sbPasswd, anFinal[1] << 16 | anFinal[7] << 8 | anFinal[13], 4); to64(sbPasswd, anFinal[2] << 16 | anFinal[8] << 8 | anFinal[14], 4); to64(sbPasswd, anFinal[3] << 16 | anFinal[9] << 8 | anFinal[15], 4); to64(sbPasswd, anFinal[4] << 16 | anFinal[10] << 8 | anFinal[5], 4); to64(sbPasswd, anFinal[11], 2); return sbPasswd.toString(); }
00
Code Sample 1: private void importUrl(String str) throws Exception { URL url = new URL(str); InputStream xmlStream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); MessageHolder messages = MessageHolder.getInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlStream); Element rootElement = document.getDocumentElement(); EntrySetParser entrySetParser = new EntrySetParser(); EntrySetTag entrySet = entrySetParser.process(rootElement); UpdateProteinsI proteinFactory = new UpdateProteins(); BioSourceFactory bioSourceFactory = new BioSourceFactory(); ControlledVocabularyRepository.check(); EntrySetChecker.check(entrySet, proteinFactory, bioSourceFactory); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printCheckerReport(System.err); } else { EntrySetPersister.persist(entrySet); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printPersisterReport(System.err); } else { System.out.println("The data have been successfully saved in your Intact node."); } } } Code Sample 2: public void getFile(String url, String filepath) throws BggException { System.out.println(url); int retry = retryCount + 1; lastURL = url; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; BufferedInputStream bis = null; OutputStream osw = null; try { con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); setHeaders(con); con.setRequestMethod("GET"); responseCode = con.getResponseCode(); bis = new BufferedInputStream(con.getInputStream()); int data; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filepath)); while ((data = bis.read()) != -1) bos.write(data); bos.flush(); bos.close(); break; } finally { try { bis.close(); } catch (Exception ignore) { } try { osw.close(); } catch (Exception ignore) { } try { con.disconnect(); } catch (Exception ignore) { } } } catch (IOException ioe) { if (responseCode == UNAUTHORIZED || responseCode == FORBIDDEN) { throw new BggException(ioe.getMessage(), responseCode); } if (retriedCount == retryCount) { throw new BggException(ioe.getMessage(), responseCode); } } try { Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { } } }
00
Code Sample 1: @Override public boolean putUserDescription(String openID, String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { int modified = 0; PreparedStatement updSt = getConnection().prepareStatement(UPDATE_USER_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); updSt.setString(3, openID); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Query: \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Query: \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; } Code Sample 2: private static void copyFile(String src, String dest) throws IOException { File destFile = new File(dest); if (destFile.exists()) { destFile.delete(); } FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: public String jsFunction_send(String postData) { URL url = null; try { if (_uri.startsWith("http")) { url = new URL(_uri); } else { url = new URL("file://./" + _uri); } } catch (MalformedURLException e) { IdeLog.logError(ScriptingPlugin.getDefault(), Messages.WebRequest_Error, e); return StringUtils.EMPTY; } try { URLConnection conn = url.openConnection(); OutputStreamWriter wr = null; if (this._method.equals("post")) { conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postData); wr.flush(); } BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line + "\r\n"); } if (wr != null) { wr.close(); } rd.close(); String result = sb.toString(); return result; } catch (Exception e) { IdeLog.logError(ScriptingPlugin.getDefault(), Messages.WebRequest_Error, e); return StringUtils.EMPTY; } } Code Sample 2: public static String deleteTag(String tag_id) { String so = OctopusErrorMessages.UNKNOWN_ERROR; if (tag_id == null || tag_id.trim().equals("")) { return OctopusErrorMessages.TAG_ID_CANT_BE_EMPTY; } DBConnection theConnection = null; try { theConnection = DBServiceManager.allocateConnection(); theConnection.setAutoCommit(false); String query = "DELETE FROM tr_translation WHERE tr_translation_trtagid=?"; PreparedStatement state = theConnection.prepareStatement(query); state.setString(1, tag_id); state.executeUpdate(); String query2 = "DELETE FROM tr_tag WHERE tr_tag_id=? "; PreparedStatement state2 = theConnection.prepareStatement(query2); state2.setString(1, tag_id); state2.executeUpdate(); theConnection.commit(); so = OctopusErrorMessages.ACTION_DONE; } catch (SQLException e) { try { theConnection.rollback(); } catch (SQLException ex) { } so = OctopusErrorMessages.ERROR_DATABASE; } finally { if (theConnection != null) { try { theConnection.setAutoCommit(true); } catch (SQLException ex) { } theConnection.release(); } } return so; }
00
Code Sample 1: public static String remove_tag(String sessionid, String absolutePathForTheSpesificTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "remove_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "remove_tag")); nameValuePairs.add(new BasicNameValuePair("absolute_tags", absolutePathForTheSpesificTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", resultJsonString); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; } Code Sample 2: public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
00
Code Sample 1: public DatabaseDefinitionFactory(final DBIf db, final String adapter) throws IOException { _db = db; LOG.debug("Loading adapter: " + adapter); final URL url = getClass().getClassLoader().getResource("adapter/" + adapter + ".properties"); _props = new Properties(); _props.load(url.openStream()); if (adapter.equals("mysql")) { _modifier = new MySQLModifier(this); } else if (adapter.equals("postgresql")) { _modifier = new PostgresModifier(this); } else if (adapter.equals("hypersonic")) { _modifier = new HSQLModifier(this); } else if (adapter.equals("oracle")) { _modifier = new OracleModifier(this); } else if (adapter.equals("mssql")) { _modifier = new MSSQLModifier(this); } else { _modifier = null; } } Code Sample 2: public static void main(String[] args) throws Exception { File rootDir = new File("C:\\dev\\workspace_fgd\\gouvqc_crggid\\WebContent\\WEB-INF\\upload"); File storeDir = new File(rootDir, "storeDir"); File workDir = new File(rootDir, "workDir"); LoggerFacade loggerFacade = new CommonsLoggingLogger(logger); final FileResourceManager frm = new SmbFileResourceManager(storeDir.getPath(), workDir.getPath(), true, loggerFacade); frm.start(); final String resourceId = "811375c8-7cae-4429-9a0e-9222f47dab45"; { if (!frm.resourceExists(resourceId)) { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); FileInputStream inputStream = new FileInputStream(resourceId); frm.createResource(txId, resourceId); OutputStream outputStream = frm.writeResource(txId, resourceId); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); frm.prepareTransaction(txId); frm.commitTransaction(txId); } } for (int i = 0; i < 30; i++) { final int index = i; new Thread() { @Override public void run() { try { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); InputStream inputStream = frm.readResource(resourceId); frm.prepareTransaction(txId); frm.commitTransaction(txId); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (début)"); } String contenu = TikaUtils.getParsedContent(inputStream, "file.pdf"); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (fin)"); } } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } catch (ResourceManagerException e) { throw new RuntimeException(e); } catch (TikaException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); } Thread.sleep(60000); frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); }
11
Code Sample 1: public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException { InputStream input = null; BufferedOutputStream bos = null; File tempUnit = null; try { URL url = null; int total = 0; try { url = new URL(urlStr); input = url.openStream(); URLConnection urlConnection; urlConnection = url.openConnection(); total = urlConnection.getContentLength(); } catch (IOException e) { throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e); } String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1); tempUnit = null; try { if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit"); File parent = tempUnit.getParentFile(); FileUtils.forceMkdir(parent); if (!tempUnit.exists()) FileUtils.touch(tempUnit); bos = new BufferedOutputStream(new FileOutputStream(tempUnit)); } catch (FileNotFoundException e) { throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (IOException e) { throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (DeployToolException e) { throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e); } logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr)); int size = -1; try { size = IOUtils.copy(input, bos); bos.flush(); } catch (IOException e) { logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit)); } if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr)); } finally { if (input != null) IOUtils.closeQuietly(input); if (bos != null) IOUtils.closeQuietly(bos); } logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath())); return tempUnit.getAbsolutePath(); } Code Sample 2: public static boolean copyFile(File sourceFile, File destinationFile) { boolean copySuccessfull = false; FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); long transferedBytes = destination.transferFrom(source, 0, source.size()); copySuccessfull = transferedBytes == source.size() ? true : false; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (source != null) { try { source.close(); } catch (IOException e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (IOException e) { e.printStackTrace(); } } } return copySuccessfull; }
11
Code Sample 1: @Test public void testGrantLicense() throws Exception { context.turnOffAuthorisationSystem(); Item item = Item.create(context); String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); LicenseUtils.grantLicense(context, item, defaultLicense); StringWriter writer = new StringWriter(); IOUtils.copy(item.getBundles("LICENSE")[0].getBitstreams()[0].retrieve(), writer); String license = writer.toString(); assertThat("testGrantLicense 0", license, equalTo(defaultLicense)); context.restoreAuthSystemState(); } Code Sample 2: @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final String url = req.getParameter("url"); if (!isAllowed(url)) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } final HttpClient client = new HttpClient(); client.getParams().setVersion(HttpVersion.HTTP_1_0); final PostMethod method = new PostMethod(url); method.getParams().setVersion(HttpVersion.HTTP_1_0); method.setFollowRedirects(false); final RequestEntity entity = new InputStreamRequestEntity(req.getInputStream()); method.setRequestEntity(entity); try { final int statusCode = client.executeMethod(method); if (statusCode != -1) { InputStream is = null; ServletOutputStream os = null; try { is = method.getResponseBodyAsStream(); try { os = resp.getOutputStream(); IOUtils.copy(is, os); } finally { if (os != null) { try { os.flush(); } catch (IOException ignored) { } } } } catch (IOException ioex) { final String message = ioex.getMessage(); if (!"chunked stream ended unexpectedly".equals(message)) { throw ioex; } } finally { IOUtils.closeQuietly(is); } } } finally { method.releaseConnection(); } }
11
Code Sample 1: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; } Code Sample 2: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void initURL(URL url, boolean cache) throws IOException { this.url = url; if (cache) { System.out.println(getClass().getName() + ": caching '" + url + "'"); InputStream urlIS = new BufferedInputStream(url.openStream(), 1024 * 30); file = File.createTempFile("_dss_", "_dss_"); file.deleteOnExit(); OutputStream cachedOS = new BufferedOutputStream(new FileOutputStream(file), 1024 * 30); byte[] buf = new byte[1024 * 4]; long cachedBytesCount = 0; int count = 0; while ((count = urlIS.read(buf)) > 0) { cachedOS.write(buf, 0, count); cachedBytesCount += count; } urlIS.close(); cachedOS.flush(); cachedOS.close(); this.cached = true; System.out.println(getClass().getName() + ": cached " + cachedBytesCount + " bytes into '" + file.getAbsolutePath() + "'"); } }
00
Code Sample 1: public static String encrypt(String x) throws Exception { MessageDigest mdEnc = MessageDigest.getInstance("SHA-1"); mdEnc.update(x.getBytes(), 0, x.length()); String md5 = new BigInteger(1, mdEnc.digest()).toString(16); return md5; } Code Sample 2: private static Long statusSWGCraftTime() { long current = System.currentTimeMillis() / 1000L; if (current < (previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY)) return previousStatusTime; URL url = null; try { synchronized (previousStatusTime) { if (current >= previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY) { url = SWGCraft.getStatusTextURL(); String statusTime = ZReader.read(url.openStream()); previousStatusTime = Long.valueOf(statusTime); previousStatusCheck = current; } return previousStatusTime; } } catch (UnknownHostException e) { SWGCraft.showUnknownHostDialog(url, e); } catch (Throwable e) { SWGAide.printDebug("cmgr", 1, "SWGResourceManager:statusSWGCraftTime:", e.toString()); } return Long.valueOf(0); }
00
Code Sample 1: public String sendSMS(String destinationNumber, String txt, String id) throws IOException { String out = ""; String smsdata = ""; smsdata += URLEncoder.encode("id", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc); smsdata += "&" + URLEncoder.encode("conversationId", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc); smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc); System.out.println("smsdata: " + smsdata); URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/"); URLConnection smsconn = smsurl.openConnection(); smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); smsconn.setRequestProperty("User-agent", USER_AGENT); smsconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream()); callwr.write(smsdata); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; } Code Sample 2: protected void doProxyInternally(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpRequestBase proxyReq = buildProxyRequest(req); URI reqUri = proxyReq.getURI(); String cookieDomain = reqUri.getHost(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute("org.atricorel.idbus.kernel.main.binding.http.HttpServletRequest", req); int intIdx = 0; for (int i = 0; i < httpClient.getRequestInterceptorCount(); i++) { if (httpClient.getRequestInterceptor(i) instanceof RequestAddCookies) { intIdx = i; break; } } IDBusRequestAddCookies interceptor = new IDBusRequestAddCookies(cookieDomain); httpClient.removeRequestInterceptorByClass(RequestAddCookies.class); httpClient.addRequestInterceptor(interceptor, intIdx); httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (logger.isTraceEnabled()) logger.trace("Staring to follow redirects for " + req.getPathInfo()); HttpResponse proxyRes = null; List<Header> storedHeaders = new ArrayList<Header>(40); boolean followTargetUrl = true; byte[] buff = new byte[1024]; while (followTargetUrl) { if (logger.isTraceEnabled()) logger.trace("Sending internal request " + proxyReq); proxyRes = httpClient.execute(proxyReq, httpContext); String targetUrl = null; Header[] headers = proxyRes.getAllHeaders(); for (Header header : headers) { if (header.getName().equals("Server")) continue; if (header.getName().equals("Transfer-Encoding")) continue; if (header.getName().equals("Location")) continue; if (header.getName().equals("Expires")) continue; if (header.getName().equals("Content-Length")) continue; if (header.getName().equals("Content-Type")) continue; storedHeaders.add(header); } if (logger.isTraceEnabled()) logger.trace("HTTP/STATUS:" + proxyRes.getStatusLine().getStatusCode() + "[" + proxyReq + "]"); switch(proxyRes.getStatusLine().getStatusCode()) { case 200: followTargetUrl = false; break; case 404: followTargetUrl = false; break; case 500: followTargetUrl = false; break; case 302: Header location = proxyRes.getFirstHeader("Location"); targetUrl = location.getValue(); if (!internalProcessingPolicy.match(req, targetUrl)) { if (logger.isTraceEnabled()) logger.trace("Do not follow HTTP 302 to [" + location.getValue() + "]"); Collections.addAll(storedHeaders, proxyRes.getHeaders("Location")); followTargetUrl = false; } else { if (logger.isTraceEnabled()) logger.trace("Do follow HTTP 302 to [" + location.getValue() + "]"); followTargetUrl = true; } break; default: followTargetUrl = false; break; } HttpEntity entity = proxyRes.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { if (!followTargetUrl) { for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } IOUtils.copy(instream, res.getOutputStream()); res.getOutputStream().flush(); } else { int r = instream.read(buff); int total = r; while (r > 0) { r = instream.read(buff); total += r; } if (total > 0) logger.warn("Ignoring response content size : " + total); } } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { proxyReq.abort(); throw ex; } finally { try { instream.close(); } catch (Exception ignore) { } } } else { if (!followTargetUrl) { res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } } } if (followTargetUrl) { proxyReq = buildProxyRequest(targetUrl); httpContext = null; } } if (logger.isTraceEnabled()) logger.trace("Ended following redirects for " + req.getPathInfo()); }
00
Code Sample 1: private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); throw new RuntimeException(e); } } Code Sample 2: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.*;"); importList.add("java.sql.Date;"); importList.add("com.emeraldjb.runtime.patternXmlObj.*;"); importList.add("javax.xml.parsers.*;"); importList.add("java.text.ParseException;"); importList.add("org.xml.sax.*;"); importList.add("org.xml.sax.helpers.*;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); boolean short_version = entity.getPatternBooleanValue(GeneratorConst.PATTERN_STREAM_XML_SHORT, false); StringBuffer preface = new StringBuffer(); StringBuffer consts = new StringBuffer(); StringBuffer f_writer = new StringBuffer(); StringBuffer f_writer_short = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); StringBuffer end_elems = new StringBuffer(); boolean end_elem_needs_catch = false; consts.append("\n public static final String EL_CLASS_TAG=\"" + values_class_name + "\";"); preface.append("\n xos.print(\"<!-- This format is optimised for space, below are the column mappings\");"); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); int col_num = 0; while (it.hasNext()) { col_num++; Member member = (Member) it.next(); String nm = member.getName(); preface.append("\n xos.print(\"c" + col_num + " = " + nm + "\");"); String elem_name = nm; String elem_name_short = "c" + col_num; String el_name = nm.toUpperCase(); if (member.getColLen() > 0 || !member.isNullAllowed()) { end_elem_needs_catch = true; } String element_const = "EL_" + el_name; String element_const_short = "EL_" + el_name + "_SHORT"; consts.append("\n public static final String " + element_const + "=\"" + elem_name + "\";" + "\n public static final String " + element_const_short + "=\"" + elem_name_short + "\";"); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "values_." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToXmlCode(pad, element_const, getter + "()")); f_writer_short.append(gen_type.getToXmlCode(pad, element_const_short, getter + "()")); end_elems.append(gen_type.getFromXmlCode(pad, element_const, setter)); end_elems.append("\n //and also the short version"); end_elems.append(gen_type.getFromXmlCode(pad, element_const_short, setter)); } preface.append("\n xos.print(\"-->\");"); String body_part = f_writer.toString(); String body_part_short = preface.toString() + f_writer_short.toString(); String reader_vars = ""; String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + " extends DefaultHandler implements TSParser\n"); sb.append("{" + consts + "\n public static final int PROTO_VERSION=" + proto_version + ";" + "\n private transient StringBuffer cdata_=new StringBuffer();" + "\n private transient String endElement_;" + "\n private transient TSParser parentParser_;" + "\n private transient XMLReader theReader_;\n" + "\n private " + values_class_name + " values_;"); sb.append("\n\n"); sb.append("\n /**" + "\n * This is really only here as an example. It is very rare to write a single" + "\n * object to a file - far more likely to have a collection or object graph. " + "\n * in which case you can write something similar - maybe using the writeXmlShort" + "\n * version instread." + "\n */" + "\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n XmlOutputFilter xos = new XmlOutputFilter(fos);" + "\n xos.openElement(\"FILE_\"+EL_CLASS_TAG);" + "\n writeXml(xos, obj);" + "\n xos.closeElement();" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException, SAXException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n marshalFromXml(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeXml(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public static void writeXmlShort(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part_short + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public " + streamer_class_name + "(" + values_class_name + " obj) {" + "\n values_ = obj;" + "\n } // end of ctor" + "\n"); String xml_bit = addXmlFunctions(streamer_class_name, values_class_name, end_elem_needs_catch, end_elems, f_reader); String close = "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"; return sb.toString() + xml_bit + close; }
11
Code Sample 1: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } } Code Sample 2: public void onUpload$btnFileUpload(UploadEvent ue) { BufferedInputStream in = null; BufferedOutputStream out = null; if (ue == null) { System.out.println("unable to upload file"); return; } else { System.out.println("fileUploaded()"); } try { Media m = ue.getMedia(); System.out.println("m.getContentType(): " + m.getContentType()); System.out.println("m.getFormat(): " + m.getFormat()); try { InputStream is = m.getStreamData(); in = new BufferedInputStream(is); File baseDir = new File(UPLOAD_PATH); if (!baseDir.exists()) { baseDir.mkdirs(); } final File file = new File(UPLOAD_PATH + m.getName()); OutputStream fout = new FileOutputStream(file); out = new BufferedOutputStream(fout); IOUtils.copy(in, out); if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) { final String filename = m.getName(); Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() { @Override public void onEvent(Event event) throws Exception { try { int response = ((Integer) event.getData()).intValue(); if (response == Messagebox.YES) { System.out.println("unzipping file to: " + UPLOAD_PATH); boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false); if (success) { Messagebox.show("File unzipped: '" + filename + "'"); } else { Messagebox.show("Unable to unzip '" + filename + "' "); } } else { System.out.println("leaving archive file alone"); } } catch (NumberFormatException nfe) { System.out.println("Not a valid response"); } } }); } else { Messagebox.show("File '" + m.getName() + "' successfully uploaded"); } } catch (IOException e) { System.out.println("IO Exception while saving file: "); e.printStackTrace(System.out); } catch (Exception e) { System.out.println("General Exception: "); e.printStackTrace(System.out); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { System.out.println("IO Exception while closing stream: "); e.printStackTrace(System.out); } } } catch (Exception e) { System.out.println("Error uploading file."); e.printStackTrace(System.out); } }
11
Code Sample 1: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; } Code Sample 2: public static File gzipLog() throws IOException { RunnerClass.nfh.flush(); File log = new File(RunnerClass.homedir + "pj.log"); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File(log.getCanonicalPath() + ".pjl"))); FileInputStream in = new FileInputStream(log); int bufferSize = 4 * 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); return new File(log.getCanonicalPath() + ".pjl"); }
11
Code Sample 1: public static File[] splitFile(FileValidator validator, File source, long target_length, File todir, String prefix) { if (target_length == 0) return null; if (todir == null) { todir = new File(System.getProperty("java.io.tmpdir")); } if (prefix == null || prefix.equals("")) { prefix = source.getName(); } Vector result = new Vector(); FileOutputStream fos = null; FileInputStream fis = null; try { fis = new FileInputStream(source); byte[] bytes = new byte[CACHE_SIZE]; long current_target_size = 0; int current_target_nb = 1; int nbread = -1; try { File f = new File(todir, prefix + i18n.getString("targetname_suffix") + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); while ((nbread = fis.read(bytes)) > -1) { if ((current_target_size + nbread) > target_length) { int limit = (int) (target_length - current_target_size); fos.write(bytes, 0, limit); fos.close(); current_target_nb++; current_target_size = 0; f = new File(todir, prefix + "_" + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); fos.write(bytes, limit, nbread - limit); current_target_size += nbread - limit; } else { fos.write(bytes, 0, nbread); current_target_size += nbread; } } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } try { if (fis != null) fis.close(); } catch (IOException e) { } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } File[] fresult = null; if (result.size() > 0) { fresult = new File[result.size()]; fresult = (File[]) result.toArray(fresult); } return fresult; } Code Sample 2: public static byte[] loadFile(File file) throws IOException { BufferedInputStream in = null; ByteArrayOutputStream sink = null; try { in = new BufferedInputStream(new FileInputStream(file)); sink = new ByteArrayOutputStream(); IOUtils.copy(in, sink); return sink.toByteArray(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(sink); } }
00
Code Sample 1: private List _getWeathersFromYahoo(String city) { System.out.println("== get weather information of " + city + " from yahoo =="); try { URL url = new URL(URL + cities.get(city).toString()); InputStream input = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); YahooHandler yh = new YahooHandler(); yh.setCity(city); parser.parse(input, yh); return yh.getWeathers(); } catch (MalformedURLException e) { throw new WeatherException("MalformedURLException"); } catch (IOException e) { throw new WeatherException("无法读取数据。"); } catch (ParserConfigurationException e) { throw new WeatherException("ParserConfigurationException"); } catch (SAXException e) { throw new WeatherException("数据格式错误,无法解析。"); } } 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 InputStream getInputStream(URL url) throws IOException { if (url.getProtocol().equals("file")) { String path = decode(url.getPath(), "UTF-8"); return new BufferedInputStream(new FileInputStream(path)); } else { return new BufferedInputStream(url.openStream()); } } Code Sample 2: 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) { } } } }
00
Code Sample 1: public T_Result unmarshall(URL url) throws SAXException, ParserConfigurationException, IOException { XMLReader parser = getParserFactory().newSAXParser().getXMLReader(); parser.setContentHandler(getContentHandler()); parser.setDTDHandler(getContentHandler()); parser.setEntityResolver(getContentHandler()); parser.setErrorHandler(getContentHandler()); InputSource inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); parser.parse(inputSource); return contentHandler.getRootObject(); } Code Sample 2: private static ISimpleChemObjectReader createReader(URL url, String urlString, String type) throws CDKException { if (type == null) { type = "mol"; } ISimpleChemObjectReader cor = null; cor = new MDLV2000Reader(getReader(url), Mode.RELAXED); try { ReaderFactory factory = new ReaderFactory(); cor = factory.createReader(getReader(url)); if (cor instanceof CMLReader) { cor = new CMLReader(urlString); } } catch (IOException ioExc) { } catch (Exception exc) { } if (cor == null) { if (type.equals(JCPFileFilter.cml) || type.equals(JCPFileFilter.xml)) { cor = new CMLReader(urlString); } else if (type.equals(JCPFileFilter.sdf)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.mol)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.inchi)) { try { cor = new INChIReader(new URL(urlString).openStream()); } catch (MalformedURLException e) { } catch (IOException e) { } } else if (type.equals(JCPFileFilter.rxn)) { cor = new MDLRXNV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.smi)) { cor = new SMILESReader(getReader(url)); } } if (cor == null) { throw new CDKException(GT._("Could not determine file format")); } if (cor instanceof MDLV2000Reader) { try { BufferedReader in = new BufferedReader(getReader(url)); String line; while ((line = in.readLine()) != null) { if (line.equals("$$$$")) { String message = GT._("It seems you opened a mol or sdf" + " file containing several molecules. " + "Only the first one will be shown"); JOptionPane.showMessageDialog(null, message, GT._("sdf-like file"), JOptionPane.INFORMATION_MESSAGE); break; } } } catch (IOException ex) { } } return cor; }
00
Code Sample 1: public static String md5(String input) { byte[] temp; try { MessageDigest messageDigest; messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(input.getBytes()); temp = messageDigest.digest(); } catch (Exception e) { return null; } return MyUtils.byte2HexStr(temp); } Code Sample 2: public void startImport(ActionEvent evt) { final PsiExchange psiExchange = PsiExchangeFactory.createPsiExchange(IntactContext.getCurrentInstance().getSpringContext()); for (final URL url : urlsToImport) { try { if (log.isInfoEnabled()) log.info("Importing: " + url); psiExchange.importIntoIntact(url.openStream()); } catch (IOException e) { handleException(e); return; } } addInfoMessage("File successfully imported", Arrays.asList(urlsToImport).toString()); }
00
Code Sample 1: @Override public synchronized HttpURLConnection getTileUrlConnection(int zoom, int tilex, int tiley) throws IOException { HttpURLConnection conn = null; try { String url = getTileUrl(zoom, tilex, tiley); conn = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { throw e; } catch (Exception e) { log.error("", e); throw new IOException(e); } try { i.set("conn", conn); i.eval("addHeaders(conn);"); } catch (EvalError e) { String msg = e.getMessage(); if (!AH_ERROR.equals(msg)) { log.error(e.getClass() + ": " + e.getMessage(), e); throw new IOException(e); } } return conn; } Code Sample 2: private void _scanForMetaData(URL _url) throws java.io.IOException { if (DEBUG.Enabled) System.out.println(this + " _scanForMetaData: xml props " + mXMLpropertyList); if (DEBUG.Enabled) System.out.println("*** Opening connection to " + _url); markAccessAttempt(); Properties metaData = scrapeHTMLmetaData(_url.openConnection(), 2048); if (DEBUG.Enabled) System.out.println("*** Got meta-data " + metaData); markAccessSuccess(); String title = metaData.getProperty("title"); if (title != null && title.length() > 0) { setProperty("title", title); title = title.replace('\n', ' ').trim(); setTitle(title); } try { setByteSize(Integer.parseInt((String) getProperty("contentLength"))); } catch (Exception e) { } }
11
Code Sample 1: public static void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[2048]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } else { System.err.println(FileUtil.class.toString() + ":不存在file" + oldPathFile); } } catch (Exception e) { System.err.println(FileUtil.class.toString() + ":复制file" + oldPathFile + "到" + newPathFile + "出错!"); } } Code Sample 2: public static void copy(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) dstDir.mkdir(); String[] children = srcDir.list(); for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i])); } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcDir); out = new FileOutputStream(dstDir); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } } }
11
Code Sample 1: public void fileCopy2(File inFile, File outFile) throws Exception { try { FileChannel srcChannel = new FileInputStream(inFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { throw new Exception("Could not copy file: " + inFile.getName()); } } Code Sample 2: public Controller(String m_hostname, String team, boolean m_shouldexit) throws InternalException { m_received_messages = new ConcurrentLinkedQueue<ReceivedMessage>(); m_fragmsgs = new ArrayList<String>(); m_customizedtaunts = new HashMap<Integer, String>(); m_nethandler = new CachingNetHandler(); m_drawingpanel = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities()); m_user = System.getProperty("user.name"); m_chatbuffer = new StringBuffer(); this.m_shouldexit = m_shouldexit; isChatPaused = false; isRunning = true; m_lastbullet = 0; try { BufferedReader in = new BufferedReader(new FileReader(HogsConstants.FRAGMSGS_FILE)); String str; while ((str = in.readLine()) != null) { m_fragmsgs.add(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } String newFile = PathFinder.getCustsFile(); boolean exists = (new File(newFile)).exists(); Reader reader = null; if (exists) { try { reader = new FileReader(newFile); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } else { Object[] options = { "Yes, create a .hogsrc file", "No, use default taunts" }; int n = JOptionPane.showOptionDialog(m_window, "You do not have customized taunts in your home\n " + "directory. Would you like to create a customizable file?", "Hogs Customization", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 0) { try { FileChannel srcChannel = new FileInputStream(HogsConstants.CUSTS_TEMPLATE).getChannel(); FileChannel dstChannel; dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); reader = new FileReader(newFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { reader = new FileReader(HogsConstants.CUSTS_TEMPLATE); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } } try { m_netengine = NetEngine.forHost(m_user, m_hostname, 1820, m_nethandler); m_netengine.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (NetException e) { e.printStackTrace(); } m_gamestate = m_netengine.getCurrentState(); m_gamestate.setInChatMode(false); m_gamestate.setController(this); try { readFromFile(reader); } catch (NumberFormatException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } catch (InternalException e3) { e3.printStackTrace(); } GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice m_graphicsdevice = ge.getDefaultScreenDevice(); m_window = new GuiFrame(m_drawingpanel, m_gamestate); m_graphics = null; try { m_graphics = new GraphicsEngine(m_drawingpanel, m_gamestate); } catch (InternalException e1) { e1.printStackTrace(); System.exit(0); } m_drawingpanel.addGLEventListener(m_graphics); m_physics = new Physics(); if (team == null) { team = HogsConstants.TEAM_NONE; } if (!(team.toLowerCase().equals(HogsConstants.TEAM_NONE) || team.toLowerCase().equals(HogsConstants.TEAM_RED) || team.toLowerCase().equals(HogsConstants.TEAM_BLUE))) { throw new InternalException("Invalid team name!"); } String orig_team = team; Craft local_craft = m_gamestate.getLocalCraft(); if (m_gamestate.getNumCrafts() == 0) { local_craft.setTeamname(team); } else if (m_gamestate.isInTeamMode()) { if (team == HogsConstants.TEAM_NONE) { int red_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_RED); int blue_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_BLUE); String new_team; if (red_craft > blue_craft) { new_team = HogsConstants.TEAM_BLUE; } else if (red_craft < blue_craft) { new_team = HogsConstants.TEAM_RED; } else { new_team = Math.random() > 0.5 ? HogsConstants.TEAM_BLUE : HogsConstants.TEAM_RED; } m_gamestate.getLocalCraft().setTeamname(new_team); } else { local_craft.setTeamname(team); } } else { local_craft.setTeamname(HogsConstants.TEAM_NONE); if (orig_team != null) { m_window.displayText("You cannot join a team, this is an individual game."); } } if (!local_craft.getTeamname().equals(HogsConstants.TEAM_NONE)) { m_window.displayText("You are joining the " + local_craft.getTeamname() + " team."); } m_drawingpanel.setSize(m_drawingpanel.getWidth(), m_drawingpanel.getHeight()); m_middlepos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); m_curpos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); GuiKeyListener k_listener = new GuiKeyListener(); GuiMouseListener m_listener = new GuiMouseListener(); m_window.addKeyListener(k_listener); m_drawingpanel.addKeyListener(k_listener); m_window.addMouseListener(m_listener); m_drawingpanel.addMouseListener(m_listener); m_window.addMouseMotionListener(m_listener); m_drawingpanel.addMouseMotionListener(m_listener); m_drawingpanel.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.requestFocus(); }
11
Code Sample 1: public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); }
00
Code Sample 1: public synchronized void deleteDocument(final String file) throws IOException { SQLException ex = null; try { PreparedStatement findFileStmt = con.prepareStatement("SELECT ID AS \"ID\" FROM File_ WHERE Name = ?"); findFileStmt.setString(1, file); ResultSet rs = findFileStmt.executeQuery(); if (null != rs && rs.next()) { int fileId = rs.getInt("ID"); rs.close(); rs = null; PreparedStatement deleteTokensStmt = con.prepareStatement("DELETE FROM Token_ WHERE FieldID IN ( SELECT ID FROM Field_ WHERE FileID = ? )"); deleteTokensStmt.setInt(1, fileId); deleteTokensStmt.executeUpdate(); PreparedStatement deleteFieldsStmt = con.prepareStatement("DELETE FROM Field_ WHERE FileID = ?"); deleteFieldsStmt.setInt(1, fileId); deleteFieldsStmt.executeUpdate(); PreparedStatement deleteFileStmt = con.prepareStatement("DELETE FROM File_ WHERE ID = ?"); deleteFileStmt.setInt(1, fileId); deleteFileStmt.executeUpdate(); deleteFileStmt.close(); deleteFileStmt = null; deleteFieldsStmt.close(); deleteFieldsStmt = null; deleteTokensStmt.close(); deleteTokensStmt = null; } findFileStmt.close(); findFileStmt = null; } catch (SQLException e) { e.printStackTrace(); ex = e; try { this.con.rollback(); } catch (SQLException e2) { } } finally { try { this.con.setAutoCommit(true); } catch (SQLException e2) { } } if (null != ex) throw new IOException(ex.getMessage()); } Code Sample 2: public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } }
11
Code Sample 1: public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public static String getURLContent(String urlStr) throws MalformedURLException, IOException { URL url = new URL(urlStr); log.info("url: " + url); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer buf = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } in.close(); return buf.toString(); } Code Sample 2: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
00
Code Sample 1: public static void compressFile(File orig) throws IOException { File file = new File(INPUT + orig.toString()); File target = new File(OUTPUT + orig.toString().replaceAll(".xml", ".xml.gz")); System.out.println(" Compressing \"" + file.getName() + "\" into \"" + target + "\""); long l = file.length(); FileInputStream fileinputstream = new FileInputStream(file); GZIPOutputStream gzipoutputstream = new GZIPOutputStream(new FileOutputStream(target)); byte abyte0[] = new byte[1024]; int i; while ((i = fileinputstream.read(abyte0)) != -1) gzipoutputstream.write(abyte0, 0, i); fileinputstream.close(); gzipoutputstream.close(); long l1 = target.length(); System.out.println(" Initial size: " + l + "; Compressed size: " + l1 + "."); System.out.println(" Done."); System.out.println(); } Code Sample 2: private byte[] szyfrujKlucz(byte[] kluczSesyjny) { byte[] zaszyfrowanyKlucz = null; byte[] klucz = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); int resztaKlucza = this.dlugoscKlucza % ROZMIAR_BLOKU; if (resztaKlucza == 0) { klucz = kluczSesyjny; zaszyfrowanyKlucz = new byte[this.dlugoscKlucza]; } else { int liczbaBlokow = this.dlugoscKlucza / ROZMIAR_BLOKU + 1; int nowyRozmiar = liczbaBlokow * ROZMIAR_BLOKU; zaszyfrowanyKlucz = new byte[nowyRozmiar]; klucz = new byte[nowyRozmiar]; byte roznica = (byte) (ROZMIAR_BLOKU - resztaKlucza); System.arraycopy(kluczSesyjny, 0, klucz, 0, kluczSesyjny.length); for (int i = kluczSesyjny.length; i < nowyRozmiar; i++) klucz[i] = (byte) roznica; } byte[] szyfrogram = null; int liczbaBlokow = klucz.length / ROZMIAR_BLOKU; int offset = 0; for (offset = 0; offset < liczbaBlokow; offset++) { szyfrogram = MARS_Algorithm.blockEncrypt(klucz, offset * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(szyfrogram, 0, zaszyfrowanyKlucz, offset * ROZMIAR_BLOKU, szyfrogram.length); } } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return zaszyfrowanyKlucz; }
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 generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = outputLocation.toFile(); ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return; } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
11
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void main(String[] args) { String command = "java -jar "; String linkerJarPath = ""; String path = ""; String osName = System.getProperty("os.name"); String temp = Launcher.class.getResource("").toString(); int index = temp.indexOf(".jar"); int start = index - 1; while (Character.isLetter(temp.charAt(start))) { start--; } String jarName = temp.substring(start + 1, index + 4); System.out.println(jarName); if (osName.startsWith("Linux")) { temp = temp.substring(temp.indexOf("/"), temp.indexOf(jarName)); } else if (osName.startsWith("Windows")) { temp = temp.substring(temp.indexOf("file:") + 5, temp.indexOf(jarName)); } else { System.exit(0); } path = path + temp; try { path = java.net.URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File dir = new File(path); File[] files = dir.listFiles(); String exeJarName = null; for (File f : files) { if (f.getName().endsWith(".jar") && !f.getName().startsWith(jarName)) { exeJarName = f.getName(); break; } } if (exeJarName == null) { System.out.println("no exefile"); System.exit(0); } linkerJarPath = path + exeJarName; String pluginDirPath = path + "plugin" + File.separator; File[] plugins = new File(pluginDirPath).listFiles(); StringBuffer pluginNames = new StringBuffer(""); for (File plugin : plugins) { if (plugin.getAbsolutePath().endsWith(".jar")) { pluginNames.append("plugin/" + plugin.getName() + " "); } } String libDirPath = path + "lib" + File.separator; File[] libs = new File(libDirPath).listFiles(); StringBuffer libNames = new StringBuffer(""); for (File lib : libs) { if (lib.getAbsolutePath().endsWith(".jar")) { libNames.append("lib/" + lib.getName() + " "); } } try { JarFile jarFile = new JarFile(linkerJarPath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { manifest = new Manifest(); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Class-Path", pluginNames.toString() + libNames.toString()); String backupFile = linkerJarPath + "back"; FileInputStream copyInput = new FileInputStream(linkerJarPath); FileOutputStream copyOutput = new FileOutputStream(backupFile); byte[] buffer = new byte[4096]; int s; while ((s = copyInput.read(buffer)) > -1) { copyOutput.write(buffer, 0, s); } copyOutput.flush(); copyOutput.close(); copyInput.close(); JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(linkerJarPath), manifest); JarInputStream jarIn = new JarInputStream(new FileInputStream(backupFile)); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } jarOut.flush(); jarOut.close(); jarIn.close(); File file = new File(backupFile); if (file.exists()) { file.delete(); } } catch (IOException e1) { e1.printStackTrace(); } try { if (System.getProperty("os.name").startsWith("Linux")) { Runtime runtime = Runtime.getRuntime(); String[] commands = new String[] { "java", "-jar", path + exeJarName }; runtime.exec(commands); } else { path = path.substring(1); command = command + "\"" + path + exeJarName + "\""; System.out.println(command); Runtime.getRuntime().exec(command); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static void copyFile(File in, File out) throws EnhancedException { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (Exception e) { throw new EnhancedException("Could not copy file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + ".", e); } } Code Sample 2: public Object sendObjectRequestToSpecifiedServer(java.lang.String serverName, java.lang.String servletName, java.lang.Object request) { Object reqxml = null; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { java.net.URL url = new java.net.URL("http://" + serverName + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream os = urlconn.getOutputStream(); java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.ObjectOutputStream dos = new java.io.ObjectOutputStream(gop); dos.writeObject(request); dos.flush(); dos.close(); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.ObjectInputStream br = new java.io.ObjectInputStream(gip); reqxml = br.readObject(); } catch (Exception exp) { exp.printStackTrace(System.out); System.out.println("Exception in Servlet Connector: " + exp); } return reqxml; }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } } Code Sample 2: protected byte[] readGZippedBytes(TupleInput in) { final boolean is_compressed = in.readBoolean(); byte array[] = readBytes(in); if (array == null) return null; if (!is_compressed) { return array; } try { ByteArrayInputStream bais = new ByteArrayInputStream(array); GZIPInputStream gzin = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); IOUtils.copyTo(gzin, baos); gzin.close(); bais.close(); return baos.toByteArray(); } catch (IOException err) { throw new RuntimeException(err); } }
11
Code Sample 1: private boolean readRemoteFile() { InputStream inputstream; Concept concept = new Concept(); try { inputstream = url.openStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputStreamReader); String s4; while ((s4 = bufferedreader.readLine()) != null && s4.length() > 0) { if (!parseLine(s4, concept)) { return false; } } } catch (MalformedURLException e) { logger.fatal("malformed URL, trying to read local file"); return readLocalFile(); } catch (IOException e1) { logger.fatal("Error reading URL file, trying to read local file"); return readLocalFile(); } catch (Exception x) { logger.fatal("Failed to readRemoteFile " + x.getMessage() + ", trying to read local file"); return readLocalFile(); } return true; } Code Sample 2: public static LinkedList Import(String url) throws Exception { LinkedList data = new LinkedList(); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String csvLine; while ((csvLine = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(csvLine, ","); CSVData cd = new CSVData(); st.nextToken(); st.nextToken(); cd.matrNumber = Integer.parseInt(st.nextToken().trim()); cd.fName = st.nextToken().trim(); cd.lName = st.nextToken().trim(); cd.email = st.nextToken().trim(); cd.stdyPath = st.nextToken().trim(); cd.sem = Integer.parseInt(st.nextToken().trim()); data.add(cd); } in.close(); return data; }
11
Code Sample 1: public void create_list() { try { String data = URLEncoder.encode("PHPSESSID", "UTF-8") + "=" + URLEncoder.encode(this.get_session(), "UTF-8"); URL url = new URL(URL_LOLA + FILE_CREATE_LIST); 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())); String line; line = rd.readLine(); wr.close(); rd.close(); System.out.println("Gene list saved in LOLA"); } catch (Exception e) { System.out.println("error in createList()"); e.printStackTrace(); } } Code Sample 2: private List parseUrlGetUids(String url) throws FetchError { List hids = new ArrayList(); try { InputStream is = (new URL(url)).openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String inputLine = ""; Pattern pattern = Pattern.compile("\\<input\\s+type=hidden\\s+name=hid\\s+value=(\\d+)\\s?\\>", Pattern.CASE_INSENSITIVE); while ((inputLine = in.readLine()) != null) { Matcher matcher = pattern.matcher(inputLine); if (matcher.find()) { String id = matcher.group(1); if (!hids.contains(id)) { hids.add(id); } } } } catch (Exception e) { System.out.println(e); throw new FetchError(e); } return hids; }
00
Code Sample 1: public static String getMD5(String s) throws Exception { MessageDigest complete = MessageDigest.getInstance("MD5"); complete.update(s.getBytes()); byte[] b = complete.digest(); String result = ""; for (int i = 0; i < b.length; i++) { result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1); } return result; } Code Sample 2: private InputStream callService(String text) { InputStream in = null; try { URL url = new URL(SERVLET_URL); URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.connect(); DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); dataStream.writeBytes(text); dataStream.flush(); dataStream.close(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; }
11
Code Sample 1: @Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } } 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(); } } }
00
Code Sample 1: @Override public void copyFile2File(final File src, final File dest, final boolean force) throws C4JException { if (dest.exists()) if (force && !dest.delete()) throw new C4JException(format("Copying ‘%s’ to ‘%s’ failed; cannot overwrite existing file.", src.getPath(), dest.getPath())); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (src.canExecute()) dest.setExecutable(true, false); } catch (final IOException e) { throw new C4JException(format("Could not copy ‘%s’ to ‘%s’.", src.getPath(), dest.getPath()), e); } finally { if (inChannel != null) try { try { inChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close input stream for ‘%s’.", src.getPath()), e); } } finally { if (outChannel != null) try { outChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close output stream for ‘%s’.", dest.getPath()), e); } } } } Code Sample 2: public static synchronized String toMD5(String str) { Nulls.failIfNull(str, "Cannot create an MD5 encryption form a NULL string"); String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance(MD5); md5.update(str.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); return Strings.padLeft(hashword, 32, "0"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return hashword; }
00
Code Sample 1: public static String SHA256(String source) { logger.info(source); String result = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(source.getBytes()); byte[] bytes = digest.digest(); result = EncodeUtils.hexEncode(bytes); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } logger.info(result); return result; } Code Sample 2: protected Control createContents(Composite parent) { this.getShell().setText("Chisio"); this.getShell().setSize(800, 600); this.getShell().setImage(ImageDescriptor.createFromFile(ChisioMain.class, "icon/chisio-icon.png").createImage()); Composite composite = new Composite(parent, SWT.BORDER); composite.setLayout(new FillLayout()); this.viewer = new ScrollingGraphicalViewer(); this.viewer.setEditDomain(this.editDomain); this.viewer.createControl(composite); this.viewer.getControl().setBackground(ColorConstants.white); this.rootEditPart = new ChsScalableRootEditPart(); this.viewer.setRootEditPart(this.rootEditPart); this.viewer.setEditPartFactory(new ChsEditPartFactory()); ((FigureCanvas) this.viewer.getControl()).setScrollBarVisibility(FigureCanvas.ALWAYS); this.viewer.addDropTargetListener(new ChsFileDropTargetListener(this.viewer, this)); this.viewer.addDragSourceListener(new ChsFileDragSourceListener(this.viewer)); CompoundModel model = new CompoundModel(); model.setAsRoot(); this.viewer.setContents(model); this.viewer.getControl().addMouseListener(this); this.popupManager = new PopupManager(this); this.popupManager.setRemoveAllWhenShown(true); this.popupManager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { ChisioMain.this.popupManager.createActions(manager); } }); KeyHandler keyHandler = new KeyHandler(); ActionRegistry a = new ActionRegistry(); keyHandler.put(KeyStroke.getPressed(SWT.DEL, 127, 0), new DeleteAction(this.viewer)); keyHandler.put(KeyStroke.getPressed('+', SWT.KEYPAD_ADD, 0), new ZoomAction(this, 1, null)); keyHandler.put(KeyStroke.getPressed('-', SWT.KEYPAD_SUBTRACT, 0), new ZoomAction(this, -1, null)); keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), a.getAction(GEFActionConstants.DIRECT_EDIT)); this.viewer.setKeyHandler(keyHandler); this.higlightColor = ColorConstants.yellow; this.createCombos(); return composite; }
11
Code Sample 1: protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } state = CONNECTED; logger.info("Successfully logged in"); version = determineVersion(); writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); } Code Sample 2: protected byte[] getHashedID(String ID) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(ID.getBytes()); byte[] digest = md5.digest(); byte[] bytes = new byte[WLDB_ID_SIZE]; for (int i = 0; i < bytes.length; i++) { bytes[i] = digest[i]; } return bytes; } catch (NoSuchAlgorithmException exception) { System.err.println("Java VM is not compatible"); exit(); return null; } }
11
Code Sample 1: @Test public void testWriteAndReadSecondLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile directory2 = new RFile(directory1, "directory2"); RFile file = new RFile(directory2, "testreadwrite2nd.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } Code Sample 2: public void init(String[] arguments) { if (arguments.length < 1) { printHelp(); return; } String[] valid_args = new String[] { "device*", "d*", "help", "h", "speed#", "s#", "file*", "f*", "gpsd*", "nmea", "n", "garmin", "g", "sirf", "i", "rawdata", "downloadtracks", "downloadwaypoints", "downloadroutes", "deviceinfo", "printposonce", "printpos", "p", "printalt", "printspeed", "printheading", "printsat", "template*", "outfile*", "screenshot*", "printdefaulttemplate", "helptemplate", "nmealogfile*", "l", "uploadtracks", "uploadroutes", "uploadwaypoints", "infile*" }; CommandArguments args = null; try { args = new CommandArguments(arguments, valid_args); } catch (CommandArgumentException cae) { System.err.println("Invalid arguments: " + cae.getMessage()); printHelp(); return; } String filename = null; String serial_port_name = null; boolean gpsd = false; String gpsd_host = "localhost"; int gpsd_port = 2947; int serial_port_speed = -1; GPSDataProcessor gps_data_processor; String nmea_log_file = null; if (args.isSet("help") || (args.isSet("h"))) { printHelp(); return; } if (args.isSet("helptemplate")) { printHelpTemplate(); } if (args.isSet("printdefaulttemplate")) { System.out.println(DEFAULT_TEMPLATE); } if (args.isSet("device")) { serial_port_name = (String) args.getValue("device"); } else if (args.isSet("d")) { serial_port_name = (String) args.getValue("d"); } if (args.isSet("speed")) { serial_port_speed = ((Integer) args.getValue("speed")).intValue(); } else if (args.isSet("s")) { serial_port_speed = ((Integer) args.getValue("s")).intValue(); } if (args.isSet("file")) { filename = (String) args.getValue("file"); } else if (args.isSet("f")) { filename = (String) args.getValue("f"); } if (args.isSet("gpsd")) { gpsd = true; String gpsd_host_port = (String) args.getValue("gpsd"); if (gpsd_host_port != null && gpsd_host_port.length() > 0) { String[] params = gpsd_host_port.split(":"); gpsd_host = params[0]; if (params.length > 0) { gpsd_port = Integer.parseInt(params[1]); } } } if (args.isSet("garmin") || args.isSet("g")) { gps_data_processor = new GPSGarminDataProcessor(); serial_port_speed = 9600; if (filename != null) { System.err.println("ERROR: Cannot read garmin data from file, only serial port supported!"); return; } } else if (args.isSet("sirf") || args.isSet("i")) { gps_data_processor = new GPSSirfDataProcessor(); serial_port_speed = 19200; if (filename != null) { System.err.println("ERROR: Cannot read sirf data from file, only serial port supported!"); return; } } else { gps_data_processor = new GPSNmeaDataProcessor(); serial_port_speed = 4800; } if (args.isSet("nmealogfile") || (args.isSet("l"))) { if (args.isSet("nmealogfile")) nmea_log_file = args.getStringValue("nmealogfile"); else nmea_log_file = args.getStringValue("l"); } if (args.isSet("rawdata")) { gps_data_processor.addGPSRawDataListener(new GPSRawDataListener() { public void gpsRawDataReceived(char[] data, int offset, int length) { System.out.println("RAWLOG: " + new String(data, offset, length)); } }); } GPSDevice gps_device; Hashtable environment = new Hashtable(); if (filename != null) { environment.put(GPSFileDevice.PATH_NAME_KEY, filename); gps_device = new GPSFileDevice(); } else if (gpsd) { environment.put(GPSNetworkGpsdDevice.GPSD_HOST_KEY, gpsd_host); environment.put(GPSNetworkGpsdDevice.GPSD_PORT_KEY, new Integer(gpsd_port)); gps_device = new GPSNetworkGpsdDevice(); } else { if (serial_port_name != null) environment.put(GPSSerialDevice.PORT_NAME_KEY, serial_port_name); if (serial_port_speed > -1) environment.put(GPSSerialDevice.PORT_SPEED_KEY, new Integer(serial_port_speed)); gps_device = new GPSSerialDevice(); } try { gps_device.init(environment); gps_data_processor.setGPSDevice(gps_device); gps_data_processor.open(); gps_data_processor.addProgressListener(this); if ((nmea_log_file != null) && (nmea_log_file.length() > 0)) { gps_data_processor.addGPSRawDataListener(new GPSRawDataFileLogger(nmea_log_file)); } if (args.isSet("deviceinfo")) { System.out.println("GPSInfo:"); String[] infos = gps_data_processor.getGPSInfo(); for (int index = 0; index < infos.length; index++) { System.out.println(infos[index]); } } if (args.isSet("screenshot")) { FileOutputStream out = new FileOutputStream((String) args.getValue("screenshot")); BufferedImage image = gps_data_processor.getScreenShot(); ImageIO.write(image, "PNG", out); } boolean print_waypoints = args.isSet("downloadwaypoints"); boolean print_routes = args.isSet("downloadroutes"); boolean print_tracks = args.isSet("downloadtracks"); if (print_waypoints || print_routes || print_tracks) { VelocityContext context = new VelocityContext(); if (print_waypoints) { List waypoints = gps_data_processor.getWaypoints(); if (waypoints != null) context.put("waypoints", waypoints); else print_waypoints = false; } if (print_tracks) { List tracks = gps_data_processor.getTracks(); if (tracks != null) context.put("tracks", tracks); else print_tracks = false; } if (print_routes) { List routes = gps_data_processor.getRoutes(); if (routes != null) context.put("routes", routes); else print_routes = false; } context.put("printwaypoints", new Boolean(print_waypoints)); context.put("printtracks", new Boolean(print_tracks)); context.put("printroutes", new Boolean(print_routes)); Writer writer; Reader reader; if (args.isSet("template")) { String template_file = (String) args.getValue("template"); reader = new FileReader(template_file); } else { reader = new StringReader(DEFAULT_TEMPLATE); } if (args.isSet("outfile")) writer = new FileWriter((String) args.getValue("outfile")); else writer = new OutputStreamWriter(System.out); addDefaultValuesToContext(context); boolean result = printTemplate(context, reader, writer); } boolean read_waypoints = (args.isSet("uploadwaypoints") && args.isSet("infile")); boolean read_routes = (args.isSet("uploadroutes") && args.isSet("infile")); boolean read_tracks = (args.isSet("uploadtracks") && args.isSet("infile")); if (read_waypoints || read_routes || read_tracks) { ReadGPX reader = new ReadGPX(); String in_file = (String) args.getValue("infile"); reader.parseFile(in_file); if (read_waypoints) gps_data_processor.setWaypoints(reader.getWaypoints()); if (read_routes) gps_data_processor.setRoutes(reader.getRoutes()); if (read_tracks) gps_data_processor.setTracks(reader.getTracks()); } if (args.isSet("printposonce")) { GPSPosition pos = gps_data_processor.getGPSPosition(); System.out.println("Current Position: " + pos); } if (args.isSet("printpos") || args.isSet("p")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.LOCATION, this); } if (args.isSet("printalt")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.ALTITUDE, this); } if (args.isSet("printspeed")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SPEED, this); } if (args.isSet("printheading")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.HEADING, this); } if (args.isSet("printsat")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.NUMBER_SATELLITES, this); gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SATELLITE_INFO, this); } if (args.isSet("printpos") || args.isSet("p") || args.isSet("printalt") || args.isSet("printsat") || args.isSet("printspeed") || args.isSet("printheading")) { gps_data_processor.startSendPositionPeriodically(1000L); try { System.in.read(); } catch (IOException ignore) { } } gps_data_processor.close(); } catch (GPSException e) { e.printStackTrace(); } catch (FileNotFoundException fnfe) { System.err.println("ERROR: File not found: " + fnfe.getMessage()); } catch (IOException ioe) { System.err.println("ERROR: I/O Error: " + ioe.getMessage()); } }
11
Code Sample 1: public static int numberofLines(JApplet ja, String filename) { int count = 0; URL url = null; String FileToRead; FileToRead = "data/" + filename + ".csv"; try { url = new URL(ja.getCodeBase(), FileToRead); } catch (MalformedURLException e) { System.out.println("Malformed URL "); ja.stop(); } System.out.println(url.toString()); try { InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while ((reader.readLine()) != null) { count++; } in.close(); } catch (IOException e) { } return count; } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } } Code Sample 2: public static String encrypt(String passPhrase, String password) { String algorithm = "PBEWithMD5AndDES"; byte[] salt = new byte[8]; int iterations = 20; byte[] output = new byte[128]; if (passPhrase == null || "".equals(passPhrase) || password == null || "".equals(password)) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "Required parameter missing"); } try { Security.addProvider(new com.sun.crypto.provider.SunJCE()); KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray()); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); SecretKey secretKey = secretKeyFactory.generateSecret(keySpec); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(passPhrase.getBytes()); byte[] input = new byte[password.length()]; input = password.getBytes(); messageDigest.update(input); byte[] digest = messageDigest.digest(); System.arraycopy(digest, 0, salt, 0, 8); AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(salt, iterations); Cipher cipher = Cipher.getInstance(algorithm); int mode = Cipher.ENCRYPT_MODE; cipher.init(mode, secretKey, algorithmParameterSpec); output = cipher.doFinal(input); } catch (NoSuchAlgorithmException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "Algorithm not found", e); } catch (InvalidAlgorithmParameterException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "nvalidAlgorithmParameter", e); } catch (InvalidKeySpecException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "InvalidKeySpec", e); } catch (InvalidKeyException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "InvalidKey", e); } catch (NoSuchPaddingException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "NoSuchPadding", e); } catch (BadPaddingException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "BadPadding", e); } catch (IllegalBlockSizeException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "IllegalBlockSize", e); } StringBuffer result = new StringBuffer(); for (int i = 0; i < output.length; i++) { result.append(Byte.toString(output[i])); } return result.toString(); }
00
Code Sample 1: private void login() throws LoginException { log.info("# iモード.netにログイン"); try { this.httpClient.getCookieStore().clear(); HttpPost post = new HttpPost(LoginUrl); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("HIDEURL", "?WM_AK=https%3a%2f%2fimode.net%2fag&path=%2fimail%2ftop&query=")); formparams.add(new BasicNameValuePair("LOGIN", "WM_LOGIN")); formparams.add(new BasicNameValuePair("WM_KEY", "0")); formparams.add(new BasicNameValuePair("MDCM_UID", this.name)); formparams.add(new BasicNameValuePair("MDCM_PWD", this.pass)); UrlEncodedFormEntity entity = null; try { entity = new UrlEncodedFormEntity(formparams, "UTF-8"); } catch (Exception e) { } post.setHeader("User-Agent", "Mozilla/4.0 (compatible;MSIE 7.0; Windows NT 6.0;)"); post.setEntity(entity); try { HttpResponse res = this.executeHttp(post); if (res == null) { this.logined = Boolean.FALSE; throw new IOException("Redirect Error"); } if (res.getStatusLine().getStatusCode() != 200) { this.logined = Boolean.FALSE; throw new IOException("http login response bad status code " + res.getStatusLine().getStatusCode()); } String body = toStringBody(res); if (body.indexOf("<title>認証エラー") > 0) { this.logined = Boolean.FALSE; log.info("認証エラー"); log.debug(body); this.clearCookie(); throw new LoginException("認証エラー"); } } finally { post.abort(); } post = new HttpPost(JsonUrl + "login"); try { HttpResponse res = this.requestPost(post, null); if (res == null) { this.logined = Boolean.FALSE; throw new IOException("Login Error"); } if (res.getStatusLine().getStatusCode() != 200) { this.logined = Boolean.FALSE; throw new IOException("http login2 response bad status code " + res.getStatusLine().getStatusCode()); } this.logined = Boolean.TRUE; } finally { post.abort(); } } catch (Exception e) { this.logined = Boolean.FALSE; throw new LoginException("Docomo i mode.net Login Error.", e); } } Code Sample 2: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
11
Code Sample 1: private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; } Code Sample 2: public void xtest7() throws Exception { System.out.println("Lowagie"); FileInputStream inputStream = new FileInputStream("C:/Temp/arquivo.pdf"); PDFBoxManager manager = new PDFBoxManager(); InputStream[] images = manager.toImage(inputStream, "jpeg"); int count = 0; for (InputStream image : images) { FileOutputStream outputStream = new FileOutputStream("C:/Temp/arquivo_" + count + ".jpg"); IOUtils.copy(image, outputStream); count++; outputStream.close(); } inputStream.close(); }
11
Code Sample 1: public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } Code Sample 2: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void copyFile(File sourceFile, File targetFile) throws IOException { FileInputStream iStream = new FileInputStream(sourceFile); FileOutputStream oStream = new FileOutputStream(targetFile); FileChannel inChannel = iStream.getChannel(); FileChannel outChannel = oStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); int readCount = inChannel.read(buffer); if (readCount == -1) { break; } buffer.flip(); outChannel.write(buffer); } iStream.close(); oStream.close(); } Code Sample 2: private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException { ZipOutputStream zipOutput = null; try { zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); for (File file : files) { BufferedInputStream fileInput = null; File cachePathName = new File(cacheFolder, file.getPath()); try { if (!cachePathName.exists()) { throw new CacheOperationException("Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it " + "has gone missing (cause unknown). This can indicate implementation or deployment " + "error. Aborting export operation as a safety precaution.", cachePathName.getPath(), target.getAbsolutePath(), account.getOid()); } fileInput = new BufferedInputStream(new FileInputStream(cachePathName)); ZipEntry entry = new ZipEntry(file.getPath()); entry.setSize(cachePathName.length()); entry.setTime(cachePathName.lastModified()); zipOutput.putNextEntry(entry); cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath()); int count, total = 0; int buffer = 2048; byte[] data = new byte[buffer]; while ((count = fileInput.read(data, 0, buffer)) != -1) { zipOutput.write(data, 0, count); total += count; } zipOutput.flush(); if (total != cachePathName.length()) { throw new CacheOperationException("Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). " + "This could have occured either due implementation error or file I/O error. " + "Aborting archive operation to prevent a potentially corrupt export archive to " + "be created.", total, cachePathName.length(), cachePathName.getPath(), account.getOid()); } else { cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total, cachePathName.length(), file.getPath()); } } catch (SecurityException e) { throw new ConfigurationException("Security manager has denied r/w access when attempting to read file ''{0}'' and " + "write it to archive ''{1}'' (Account : {2}) : {3}", e, cachePathName.getPath(), target, account.getOid(), e.getMessage()); } catch (IllegalArgumentException e) { throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (FileNotFoundException e) { throw new CacheOperationException("Attempted to include file ''{0}'' in export archive but it has gone missing " + "(Account : {1}). Possible implementation error in local file cache. Aborting " + "export operation as a precaution ({2})", e, cachePathName.getPath(), account.getOid(), e.getMessage()); } catch (ZipException e) { throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (IOException e) { throw new CacheOperationException("I/O error while creating export archive for account ID = {0}. " + "Operation aborted ({1})", e, account.getOid(), e.getMessage()); } finally { if (zipOutput != null) { try { zipOutput.closeEntry(); } catch (Throwable t) { cacheLog.warn("Unable to close zip entry for file ''{0}'' in export archive ''{1}'' " + "(Account : {2}) : {3}.", t, file.getPath(), target.getAbsolutePath(), account.getOid(), t.getMessage()); } } if (fileInput != null) { try { fileInput.close(); } catch (Throwable t) { cacheLog.warn("Failed to close input stream from file ''{0}'' being added " + "to export archive (Account : {1}) : {2}", t, cachePathName.getPath(), account.getOid(), t.getMessage()); } } } } } catch (FileNotFoundException e) { throw new CacheOperationException("Unable to create target export archive ''{0}'' for account {1) : {2}", e, target, account.getOid(), e.getMessage()); } finally { try { if (zipOutput != null) { zipOutput.close(); } } catch (Throwable t) { cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target, t.getMessage()); } } }