label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
public static 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"); return null; } }
Code Sample 2:
public static String crypt(String target) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(target.getBytes("UTF-16")); BigInteger res = new BigInteger(1, md.digest(key.getBytes())); return res.toString(16); }
|
00
|
Code Sample 1:
public static void copyFile(File source, File destination) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel destChannel = new FileOutputStream(destination).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, maxCount, destChannel); } } finally { if (srcChannel != null) srcChannel.close(); if (destChannel != null) destChannel.close(); } }
Code Sample 2:
public void testJDBCSavepoints() throws Exception { String sql; String msg; int i; PreparedStatement ps; ResultSet rs; Savepoint sp1; Savepoint sp2; Savepoint sp3; Savepoint sp4; Savepoint sp5; Savepoint sp6; Savepoint sp7; int rowcount = 0; sql = "drop table t if exists"; stmt.executeUpdate(sql); sql = "create table t(id int, fn varchar, ln varchar, zip int)"; stmt.executeUpdate(sql); conn1.setAutoCommit(true); conn1.setAutoCommit(false); sql = "insert into t values(?,?,?,?)"; ps = conn1.prepareStatement(sql); ps.setString(2, "Mary"); ps.setString(3, "Peterson-Clancy"); i = 0; for (; i < 10; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp1 = conn1.setSavepoint("savepoint1"); for (; i < 20; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp2 = conn1.setSavepoint("savepoint2"); for (; i < 30; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp3 = conn1.setSavepoint("savepoint3"); for (; i < 40; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp4 = conn1.setSavepoint("savepoint4"); for (; i < 50; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp5 = conn1.setSavepoint("savepoint5"); sp6 = conn1.setSavepoint("savepoint6"); sp7 = conn1.setSavepoint("savepoint7"); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) from t value"; try { assertEquals(msg, 50, rowcount); } catch (Exception e) { } conn2.setAutoCommit(false); conn2.setSavepoint("savepoint1"); conn2.setSavepoint("savepoint2"); msg = "savepoint released succesfully on non-originating connection"; try { conn2.releaseSavepoint(sp2); assertTrue(msg, false); } catch (Exception e) { } try { conn2.rollback(sp1); msg = "succesful rollback to savepoint on " + "non-originating connection"; assertTrue(msg, false); } catch (Exception e) { } msg = "direct execution of <release savepoint> statement failed to " + "release JDBC-created SQL-savepoint with identical savepoint name"; try { conn2.createStatement().executeUpdate("release savepoint \"savepoint2\""); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } msg = "direct execution of <rollback to savepoint> statement failed to " + "roll back to existing JDBC-created SQL-savepoint with identical " + "savepoint name"; try { conn2.createStatement().executeUpdate("rollback to savepoint \"savepoint1\""); } catch (Exception e) { e.printStackTrace(); try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.releaseSavepoint(sp6); msg = "savepoint released succesfully > 1 times"; try { conn1.releaseSavepoint(sp6); assertTrue(msg, false); } catch (Exception e) { } msg = "savepoint released successfully after preceding savepoint released"; try { conn1.releaseSavepoint(sp7); assertTrue(msg, false); } catch (Exception e) { } msg = "preceding same-point savepoint destroyed by following savepoint release"; try { conn1.releaseSavepoint(sp5); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.rollback(sp4); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select * rowcount after 50 inserts - 10 rolled back:"; try { assertEquals(msg, 40, rowcount); } catch (Exception e) { } msg = "savepoint rolled back succesfully > 1 times"; try { conn1.rollback(sp4); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp3); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) after 50 inserts - 20 rolled back:"; try { assertEquals(msg, 30, rowcount); } catch (Exception e) { } msg = "savepoint released succesfully after use in rollback"; try { conn1.releaseSavepoint(sp3); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp1); msg = "savepoint rolled back without raising an exception after " + "rollback to a preceeding savepoint"; try { conn1.rollback(sp2); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(); msg = "savepoint released succesfully when it should have been " + "destroyed by a full rollback"; try { conn1.releaseSavepoint(sp1); assertTrue(msg, false); } catch (Exception e) { } conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.rollback(); conn1.setAutoCommit(false); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); }
|
11
|
Code Sample 1:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { Logger.error(FileUtil.class, ioe.getMessage(), ioe); } }
Code Sample 2:
private File copyFile(File file, String newName, File folder) { File newFile = null; if (!file.exists()) { System.out.println("File " + file + " does not exist"); return null; } if (file.isFile()) { BufferedOutputStream out = null; BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); newFile = new File(folder, newName); if (!newFile.exists()) { newFile.createNewFile(); } out = new BufferedOutputStream(new FileOutputStream(newFile)); int read; byte[] buffer = new byte[8192]; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } updateTreeUI(); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } } } else if (file.isDirectory()) { newFile = new File(folder, newName); if (!newFile.exists()) { newFile.mkdir(); } for (File f : file.listFiles()) { copyFile(f, f.getName(), newFile); } } return newFile; }
|
11
|
Code Sample 1:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { if ((this.jTree2.getSelectionPath() == null) || !(this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode)) { Msg.showMsg("Devi selezionare lo stile sotto il quale caricare la ricetta!", this); return; } if ((this.txtUser.getText() == null) || (this.txtUser.getText().length() == 0)) { Msg.showMsg("Il nome utente è obbligatorio!", this); return; } if ((this.txtPwd.getPassword() == null) || (this.txtPwd.getPassword().length == 0)) { Msg.showMsg("La password è obbligatoria!", this); return; } this.nomeRicetta = this.txtNome.getText(); if ((this.nomeRicetta == null) || (this.nomeRicetta.length() == 0)) { Msg.showMsg("Il nome della ricetta è obbligatorio!", this); return; } StyleTreeNode node = null; if (this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode) { node = (StyleTreeNode) this.jTree2.getSelectionPath().getLastPathComponent(); } try { String data = URLEncoder.encode("nick", "UTF-8") + "=" + URLEncoder.encode(this.txtUser.getText(), "UTF-8"); data += "&" + URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(new String(this.txtPwd.getPassword()), "UTF-8"); data += "&" + URLEncoder.encode("id_stile", "UTF-8") + "=" + URLEncoder.encode(node.getIdStile(), "UTF-8"); data += "&" + URLEncoder.encode("nome_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.nomeRicetta, "UTF-8"); data += "&" + URLEncoder.encode("xml_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.xml, "UTF-8"); URL url = new URL("http://" + Main.config.getRemoteServer() + "/upload_ricetta.asp?" + data); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String str = ""; while ((line = rd.readLine()) != null) { str += line; } rd.close(); Msg.showMsg(str, this); doDefaultCloseAction(); } catch (Exception e) { Utils.showException(e, "Errore in upload", this); } reloadTree(); }
Code Sample 2:
protected void handleUrl(URL url) throws Exception { File file = new File(dir.getAbsolutePath() + "/" + new Date().getTime() + "." + this.ext); FileWriter writer = new FileWriter(file); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; while ((s = in.readLine()) != null) { writer.write(s + "\n"); } in.close(); writer.close(); }
|
00
|
Code Sample 1:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ejb.bprocess.OAIPMH.AutoHarvesterSession ahSession = home.create(); java.util.Vector vector = new java.util.Vector(1, 1); Integer libraryId = new Integer(1); String xmlstr = ""; String str = ""; String arr[] = new String[2]; String[] subarr = new String[4]; String mdPrefix = "", mdPrefixValue = ""; String from = "", fromValue = ""; String until = "", untilValue = ""; String set = "", setValue = ""; String oai_pmhRequest = request.getParameter("verb"); String oai_pmhQuery = request.getQueryString(); String urlStr = ""; urlStr = "http://" + request.getServerName() + ":" + request.getServerPort() + "/newgenlibctxt/HarvestServlet"; String attribute = oai_pmhQuery; String arguments = attribute.substring(attribute.indexOf("?") + 1); StringTokenizer st = new StringTokenizer(arguments, "&"); int i = 0; int j = 0; int z = 0; int count = 0; String type = ""; while (st.hasMoreTokens()) { arr[i] = st.nextToken(); StringTokenizer subst = new StringTokenizer(arr[i], "="); while (subst.hasMoreTokens()) { subarr[j] = subst.nextToken(); j++; } i++; count++; } int mdfCount = 0, fromCount = 0, untilCount = 0, setCount = 0; ListRecords lr = new ListRecords(); for (int k = 0; k < j; k += 2) { if (subarr[k].equals("from")) { from = "from"; fromCount++; fromValue = subarr[k + 1]; fromValue = lr.validateDate(fromValue); } else if (subarr[k].equals("until")) { until = "until"; untilCount++; untilValue = subarr[k + 1]; untilValue = lr.validateDate(untilValue); } } if (fromValue.equals("") && untilCount == 1) { fromValue = lr.validateDate("0001-01-01"); } else if (untilValue.equals("") && fromCount == 1) { String a = (new Resdate()).getDate(); untilValue = a.substring(0, a.indexOf("T")); } System.out.println("This is fromValue:" + fromValue); System.out.println("This is untilValue:" + untilValue); vector = ahSession.getHarvestLibrary(null, libraryId); String harlibraryId = ""; if (vector.size() > 0) { for (int k = 0; k < vector.size(); k = k + 3) { harlibraryId = vector.elementAt(k).toString(); String harvesturl = vector.elementAt(k + 1).toString(); String status = vector.elementAt(k + 2).toString(); if (status.equals("A")) { String oai_pmhRequest1 = request.getParameter("verb"); String oai_pmhQuery1 = request.getQueryString(); urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&metadataPrefix=marc21&from=" + fromValue + "&until=" + untilValue + ""; boolean resExists = true; for (int n = 0; resExists == true; n++) { java.net.URL url = new java.net.URL(urlStr); java.net.URLConnection urlCon = url.openConnection(); urlCon.setDoInput(true); urlCon.connect(); InputStream is = urlCon.getInputStream(); System.out.println("input" + is.available()); org.jdom.input.SAXBuilder sb = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = sb.build(is); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc); System.out.println("xmlStr:" + xmlstr); doc = null; sb = null; java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); String resT = doc.getRootElement().getChildText("resumptionToken", doc.getRootElement().getNamespace()); if (!(resT == null)) { urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&resumptionToken=" + resT; } else { resExists = false; } } } else if (status.equals("B")) { java.io.File file = new java.io.File(harvesturl); java.io.File[] file1 = file.listFiles(); for (int b = 0; b < file1.length; b++) { File file2 = (File) file1[b]; System.out.println("File2:" + file2); long lastmodifed = file2.lastModified(); StringTokenizer st1 = new StringTokenizer(fromValue, "-"); String dar[] = new String[3]; java.util.Calendar c1 = java.util.Calendar.getInstance(); int g = 0; while (st1.hasMoreElements()) { dar[g] = st1.nextToken(); g++; } c1.set(Integer.parseInt(dar[0]), Integer.parseInt(dar[1]), Integer.parseInt(dar[2])); StringTokenizer st2 = new StringTokenizer(untilValue, "-"); String dar1[] = new String[3]; java.util.Calendar c2 = java.util.Calendar.getInstance(); int d = 0; while (st2.hasMoreElements()) { dar1[d] = st2.nextToken(); d++; } c2.set(Integer.parseInt(dar1[0]), Integer.parseInt(dar1[1]), Integer.parseInt(dar1[2])); java.util.Calendar c3 = java.util.Calendar.getInstance(); c3.setTimeInMillis(lastmodifed); c3.set(java.util.Calendar.HOUR, 0); c3.set(java.util.Calendar.AM_PM, java.util.Calendar.AM); c3.set(java.util.Calendar.MINUTE, 0); c3.set(java.util.Calendar.SECOND, 0); c3.set(java.util.Calendar.MILLISECOND, 0); java.util.Date d1 = c1.getTime(); java.util.Date d2 = c2.getTime(); java.util.Date d3 = c3.getTime(); System.out.println("This is d1:" + d1); System.out.println("This is d2:" + d2); System.out.println("This is d3:" + d3); if (d3.after(d1) && d3.before(d2)) { org.jdom.input.SAXBuilder sb1 = new org.jdom.input.SAXBuilder(); org.jdom.Document doc1 = sb1.build(new java.io.FileInputStream(file2)); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc1); java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); } } } } } } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); }
|
00
|
Code Sample 1:
public final boolean login(String user, String pass) { if (user == null || pass == null) return false; connectionInfo.setData("com.tensegrity.palojava.pass#" + user, pass); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); pass = asHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { throw new PaloException("Failed to create encrypted password for " + "user '" + user + "'!", ex); } connectionInfo.setUser(user); connectionInfo.setPassword(pass); return loginInternal(user, pass); }
Code Sample 2:
private String sendToServer(String request) throws IOException { Log.d("test", "request body " + request); String result = null; maybeCreateHttpClient(); HttpPost post = new HttpPost(Config.APP_BASE_URI); post.addHeader("Content-Type", "text/vnd.aexp.json.req"); post.setEntity(new StringEntity(request)); HttpResponse resp = httpClient.execute(post); int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) throw new IOException("HTTP status: " + Integer.toString(status)); DataInputStream is = new DataInputStream(resp.getEntity().getContent()); result = is.readLine(); return result; }
|
00
|
Code Sample 1:
public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; }
Code Sample 2:
@Override public String addUser(UserInfoItem user) throws DatabaseException { if (user == null) throw new NullPointerException("user"); if (user.getSurname() == null || "".equals(user.getSurname())) throw new NullPointerException("user.getSurname()"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; PreparedStatement insSt = null, updSt = null, seqSt = null; try { int modified = 0; if (user.getId() != null) { long id = Long.parseLong(user.getId()); updSt = getConnection().prepareStatement(UPDATE_USER_STATEMENT); updSt.setString(1, user.getName()); updSt.setString(2, user.getSurname()); updSt.setLong(3, id); modified = updSt.executeUpdate(); } else { insSt = getConnection().prepareStatement(INSERT_USER_STATEMENT); insSt.setString(1, user.getName()); insSt.setString(2, user.getSurname()); insSt.setBoolean(3, "m".equalsIgnoreCase(user.getSex())); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_CURR_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); } else { getConnection().rollback(); LOGGER.debug("DB has not been updated. -> rollback! Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } return retID; }
|
00
|
Code Sample 1:
public static byte[] crypt(String key, String salt) throws NoSuchAlgorithmException { int key_len = key.length(); if (salt.startsWith(saltPrefix)) { salt = salt.substring(saltPrefix.length()); } int salt_len = Math.min(getDollarLessLength(salt), 8); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); md5.update(saltPrefix.getBytes()); md5.update(salt.getBytes(), 0, salt_len); MessageDigest md5_alt = MessageDigest.getInstance("MD5"); md5_alt.update(key.getBytes()); md5_alt.update(salt.getBytes(), 0, salt_len); md5_alt.update(key.getBytes()); byte[] altResult = md5_alt.digest(); int cnt; for (cnt = key_len; cnt > 16; cnt -= 16) { md5.update(altResult, 0, 16); } md5.update(altResult, 0, cnt); altResult[0] = 0; for (cnt = key_len; cnt > 0; cnt >>= 1) { md5.update(((cnt & 1) != 0) ? altResult : key.getBytes(), 0, 1); } altResult = md5.digest(); for (cnt = 0; cnt < 1000; cnt++) { md5.reset(); if ((cnt & 1) != 0) { md5.update(key.getBytes()); } else { md5.update(altResult, 0, 16); } if ((cnt % 3) != 0) { md5.update(salt.getBytes(), 0, salt_len); } if ((cnt % 7) != 0) { md5.update(key.getBytes()); } if ((cnt & 1) != 0) { md5.update(altResult, 0, 16); } else { md5.update(key.getBytes()); } altResult = md5.digest(); } StringBuilder sb = new StringBuilder(); sb.append(saltPrefix); sb.append(new String(salt.getBytes(), 0, salt_len)); sb.append('$'); sb.append(b64From24bit(altResult[0], altResult[6], altResult[12], 4)); sb.append(b64From24bit(altResult[1], altResult[7], altResult[13], 4)); sb.append(b64From24bit(altResult[2], altResult[8], altResult[14], 4)); sb.append(b64From24bit(altResult[3], altResult[9], altResult[15], 4)); sb.append(b64From24bit(altResult[4], altResult[10], altResult[5], 4)); sb.append(b64From24bit((byte) 0, (byte) 0, altResult[11], 2)); return sb.toString().getBytes(); }
Code Sample 2:
public static void bubble_sort(Sortable[] objects) { for (int i = objects.length; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (objects[j].greater_than(objects[j + 1])) { Sortable tmp = objects[j]; objects[j] = objects[j + 1]; objects[j + 1] = tmp; flipped = true; } } if (!flipped) return; } }
|
11
|
Code Sample 1:
public boolean authorize(String username, String password, String filename) { open(filename); boolean isAuthorized = false; StringBuffer encPasswd = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } String encPassword = encPasswd.toString(); String tempPassword = getPassword(username); System.out.println("epass" + encPassword); System.out.println("pass" + tempPassword); if (tempPassword.equals(encPassword)) { isAuthorized = true; } else { isAuthorized = false; } close(); return isAuthorized; }
Code Sample 2:
public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); }
|
00
|
Code Sample 1:
public static boolean copyFileToDir(File inputFile, File outputDir) { try { String outputFileName = inputFile.getName(); int index = 1; while (existFileInDir(outputFileName, outputDir)) { outputFileName = index + inputFile.getName(); index++; } String directory = getDirectoryWithSlash(outputDir.getAbsolutePath()); File outputFile = new File(directory + outputFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { return false; } return true; }
Code Sample 2:
private ArrayList<String> getYearsAndMonths() { String info = ""; ArrayList<String> items = new ArrayList<String>(); try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf("/"); if (pos != -1) { token = token.substring(1, pos); if (Patterns.hasFormatYYYYdotMM(token)) { items.add(token); } } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return items; }
|
00
|
Code Sample 1:
public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return 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); }
|
00
|
Code Sample 1:
@Override public String fetchURL(String urlString) throws ServiceException { try { URL url = new URL(urlString); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String content = ""; String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); return content; } catch (MalformedURLException e) { throw new ServiceException(e.getMessage()); } catch (IOException e) { throw new ServiceException(e.getMessage()); } }
Code Sample 2:
public static void main(String[] args) { File file = null; try { file = File.createTempFile("TestFileChannel", ".dat"); final ByteBuffer buffer = ByteBuffer.allocateDirect(4); final ByteChannel output = new FileOutputStream(file).getChannel(); buffer.putInt(MAGIC_INT); buffer.flip(); output.write(buffer); output.close(); final ByteChannel input = new FileInputStream(file).getChannel(); buffer.clear(); while (buffer.hasRemaining()) { input.read(buffer); } input.close(); buffer.flip(); final int file_int = buffer.getInt(); if (file_int != MAGIC_INT) { System.out.println("TestFileChannel FAILURE"); System.out.println("Wrote " + Integer.toHexString(MAGIC_INT) + " but read " + Integer.toHexString(file_int)); } else { System.out.println("TestFileChannel SUCCESS"); } } catch (Exception e) { System.out.println("TestFileChannel FAILURE"); e.printStackTrace(System.out); } finally { if (null != file) { file.delete(); } } }
|
00
|
Code Sample 1:
protected Collection<BibtexEntry> getBibtexEntries(String ticket, String citations) throws IOException { try { URL url = new URL(URL_BIBTEX); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", ticket + "; " + citations); conn.connect(); BibtexParser parser = new BibtexParser(new BufferedReader(new InputStreamReader(conn.getInputStream()))); return parser.parse().getDatabase().getEntries(); } catch (MalformedURLException e) { throw new RuntimeException(e); } }
Code Sample 2:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
|
11
|
Code Sample 1:
public boolean initFile(String filename) { showStatus("Loading the file, please wait..."); x_units = "?"; y_units = "ARBITRARY"; Datatype = "UNKNOWN"; if (filename.toLowerCase().endsWith(".spc")) { try { URL url = new URL(getDocumentBase(), filename); InputStream stream = url.openStream(); DataInputStream fichier = new DataInputStream(stream); byte ftflgs = fichier.readByte(); byte fversn = fichier.readByte(); if (((ftflgs != 0) && (ftflgs != 0x20)) || (fversn != 0x4B)) { Current_Error = ", support only Evenly Spaced new version 4B"; return false; } byte fexp = fichier.readByte(); if (fexp != 0x80) YFactor = Math.pow(2, fexp) / Math.pow(2, 32); Nbpoints = NumericDataUtils.convToIntelInt(fichier.readInt()); if (Firstx == shitty_starting_constant) { Firstx = NumericDataUtils.convToIntelDouble(fichier.readLong()); Lastx = NumericDataUtils.convToIntelDouble(fichier.readLong()); } byte fxtype = fichier.readByte(); switch(fxtype) { case 0: x_units = "Arbitrary"; break; case 1: x_units = "Wavenumber (cm -1)"; break; case 2: x_units = "Micrometers"; break; case 3: x_units = "Nanometers"; break; case 4: x_units = "Seconds"; break; case 5: x_units = "Minuts"; break; case 6: x_units = "Hertz"; break; case 7: x_units = "Kilohertz"; break; case 8: x_units = "Megahertz"; break; case 9: x_units = "Mass (M/z)"; break; case 10: x_units = "Parts per million"; break; case 11: x_units = "Days"; break; case 12: x_units = "Years"; break; case 13: x_units = "Raman Shift (cm -1)"; break; case 14: x_units = "Electron Volt (eV)"; break; case 16: x_units = "Diode Number"; break; case 17: x_units = "Channel"; break; case 18: x_units = "Degrees"; break; case 19: x_units = "Temperature (F)"; break; case 20: x_units = "Temperature (C)"; break; case 21: x_units = "Temperature (K)"; break; case 22: x_units = "Data Points"; break; case 23: x_units = "Milliseconds (mSec)"; break; case 24: x_units = "Microseconds (uSec)"; break; case 25: x_units = "Nanoseconds (nSec)"; break; case 26: x_units = "Gigahertz (GHz)"; break; case 27: x_units = "Centimeters (cm)"; break; case 28: x_units = "Meters (m)"; break; case 29: x_units = "Millimeters (mm)"; break; case 30: x_units = "Hours"; break; case -1: x_units = "(double interferogram)"; break; } byte fytype = fichier.readByte(); switch(fytype) { case 0: y_units = "Arbitrary Intensity"; break; case 1: y_units = "Interfeogram"; break; case 2: y_units = "Absorbance"; break; case 3: y_units = "Kubelka-Munk"; break; case 4: y_units = "Counts"; break; case 5: y_units = "Volts"; break; case 6: y_units = "Degrees"; break; case 7: y_units = "Milliamps"; break; case 8: y_units = "Millimeters"; break; case 9: y_units = "Millivolts"; break; case 10: y_units = "Log (1/R)"; break; case 11: y_units = "Percent"; break; case 12: y_units = "Intensity"; break; case 13: y_units = "Relative Intensity"; break; case 14: y_units = "Energy"; break; case 16: y_units = "Decibel"; break; case 19: y_units = "Temperature (F)"; break; case 20: y_units = "Temperature (C)"; break; case 21: y_units = "Temperature (K)"; break; case 22: y_units = "Index of Refraction [N]"; break; case 23: y_units = "Extinction Coeff. [K]"; break; case 24: y_units = "Real"; break; case 25: y_units = "Imaginary"; break; case 26: y_units = "Complex"; break; case -128: y_units = "Transmission"; break; case -127: y_units = "Reflectance"; break; case -126: y_units = "Arbitrary or Single Beam with Valley Peaks"; break; case -125: y_units = "Emission"; break; } if (ftflgs == 0) { fichier.skipBytes(512 - 30); } else { fichier.skipBytes(188); byte b; int i = 0; x_units = ""; do { b = fichier.readByte(); x_units += (char) b; i++; } while (b != 0); int j = 0; y_units = ""; do { b = fichier.readByte(); y_units += (char) b; j++; } while (b != 0); fichier.skipBytes(512 - 30 - 188 - i - j); } fichier.skipBytes(32); My_ZoneVisu.tableau_points = new double[Nbpoints]; if (fexp == 0x80) { for (int i = 0; i < Nbpoints; i++) { My_ZoneVisu.tableau_points[i] = NumericDataUtils.convToIntelFloat(fichier.readInt()); } } else { for (int i = 0; i < Nbpoints; i++) { My_ZoneVisu.tableau_points[i] = NumericDataUtils.convToIntelInt(fichier.readInt()); } } } catch (Exception e) { Current_Error = "SPC file corrupted"; return false; } Datatype = "XYDATA"; return true; } try { URL url = new URL(getDocumentBase(), filename); InputStream stream = url.openStream(); BufferedReader fichier = new BufferedReader(new InputStreamReader(stream)); texte = new Vector(); String s; while ((s = fichier.readLine()) != null) { texte.addElement(s); } nbLignes = texte.size(); } catch (Exception e) { return false; } int My_Counter = 0; String uneligne = ""; while (My_Counter < nbLignes) { try { StringTokenizer mon_token; do { uneligne = (String) texte.elementAt(My_Counter); My_Counter++; mon_token = new StringTokenizer(uneligne, " "); } while (My_Counter < nbLignes && mon_token.hasMoreTokens() == false); if (mon_token.hasMoreTokens() == true) { String keyword = mon_token.nextToken(); if (StringDataUtils.compareStrings(keyword, "##TITLE=") == 0) TexteTitre = uneligne.substring(9); if (StringDataUtils.compareStrings(keyword, "##FIRSTX=") == 0) Firstx = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##LASTX=") == 0) Lastx = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##YFACTOR=") == 0) YFactor = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##NPOINTS=") == 0) Nbpoints = Integer.valueOf(mon_token.nextToken()).intValue(); if (StringDataUtils.compareStrings(keyword, "##XUNITS=") == 0) x_units = uneligne.substring(10); if (StringDataUtils.compareStrings(keyword, "##YUNITS=") == 0) y_units = uneligne.substring(10); if (StringDataUtils.compareStrings(keyword, "##.OBSERVE") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "FREQUENCY=") == 0) nmr_observe_frequency = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##XYDATA=") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "(X++(Y..Y))") == 0) Datatype = "XYDATA"; if (StringDataUtils.compareStrings(keyword, "##XYDATA=(X++(Y..Y))") == 0) Datatype = "XYDATA"; if (StringDataUtils.compareStrings(keyword, "##PEAK") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "TABLE=") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "(XY..XY)") == 0) Datatype = "PEAK TABLE"; if (StringDataUtils.compareStrings(keyword, "##PEAK") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "TABLE=(XY..XY)") == 0) Datatype = "PEAK TABLE"; } } catch (Exception e) { } } if (Datatype.compareTo("UNKNOWN") == 0) return false; if (Datatype.compareTo("PEAK TABLE") == 0 && x_units.compareTo("?") == 0) x_units = "M/Z"; if (StringDataUtils.truncateEndBlanks(x_units).compareTo("HZ") == 0 && nmr_observe_frequency != shitty_starting_constant) { Firstx /= nmr_observe_frequency; Lastx /= nmr_observe_frequency; x_units = "PPM."; } String resultat_move_points = Move_Points_To_Tableau(); if (resultat_move_points.compareTo("OK") != 0) { Current_Error = resultat_move_points; return false; } return true; }
Code Sample 2:
public static ISimpleChemObjectReader createReader(URL url, String urlString, String type) throws CDKException { if (type == null) { type = "mol"; } ISimpleChemObjectReader cor = null; try { Reader input = new BufferedReader(getReader(url)); FormatFactory formatFactory = new FormatFactory(8192); IChemFormat format = formatFactory.guessFormat(input); if (format != null) { if (format instanceof RGroupQueryFormat) { cor = new RGroupQueryReader(); cor.setReader(input); } else if (format instanceof CMLFormat) { cor = new CMLReader(urlString); cor.setReader(url.openStream()); } else if (format instanceof MDLV2000Format) { cor = new MDLV2000Reader(getReader(url)); cor.setReader(input); } } } catch (Exception exc) { exc.printStackTrace(); } 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 (Exception e) { e.printStackTrace(); } } 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) { ex.printStackTrace(); } } return cor; }
|
11
|
Code Sample 1:
public File copyFile(File f) throws IOException { File t = createNewFile("fm", "cpy"); FileOutputStream fos = new FileOutputStream(t); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return t; }
Code Sample 2:
public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; this.logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; this.logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; this.logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { this.logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
|
11
|
Code Sample 1:
public void deleteUser(String userID) throws XregistryException { try { userID = Utils.canonicalizeDN(userID); Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_USER_SQL_MAIN); statement1.setString(1, userID); statement1.executeUpdate(); PreparedStatement statement2 = connection.prepareStatement(DELETE_USER_SQL_DEPEND); statement2.setString(1, userID); statement2.executeUpdate(); connection.commit(); Collection<Group> groupList = groups.values(); for (Group group : groupList) { group.removeUser(userID); } log.info("Delete User " + userID); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } }
Code Sample 2:
public void addRegisterInfo(HttpServletRequest request) throws ApplicationException { String[] pids = request.getParameterValues("pid"); if (pids == null || pids.length <= 0) throw new ApplicationException("��ѡ��Ҫ���IJ�Ʒ"); RegisterDao registerDao = new RegisterDao(); Register register = registerDao.findPojoById(StrFun.getString(request, "rid"), Register.class); if (register.audit) throw new ApplicationException("��������Ѿ���ˣ��������µ���Ʒ"); DBConnect dbc = null; Connection conn = null; try { dbc = DBConnect.createDBConnect(); conn = dbc.getConnection(); conn.setAutoCommit(false); for (String pid : pids) { RegisterInfo pd = new RegisterInfo(); pd.rid = StrFun.getInt(request, "rid"); pd.pid = Integer.parseInt(pid); pd.productName = StrFun.getString(request, "productName_" + pid); pd.regAmount = StrFun.getInt(request, "regAmount_" + pid); pd.regPrice = StrFun.getInt(request, "regPrice_" + pid); pd.regSalePrice = StrFun.getInt(request, "regSalePrice_" + pid); pd.userNo = ServerUtil.getUserFromSession(request).userNo; if (pd.regAmount <= 0) throw new ApplicationException("�����������Ϊ��"); String sql = "insert into SS_RegisterInfo " + "(pid, rid, productName, regAmount, regPrice, regSalePrice, userNo) " + "values(" + "'" + pd.pid + "', " + "'" + pd.rid + "', " + "'" + pd.productName + "', " + "'" + pd.regAmount + "', " + "'" + pd.regPrice + "', " + "'" + pd.regSalePrice + "', " + "'" + pd.userNo + "' " + ")"; conn.createStatement().executeUpdate(sql); } conn.commit(); } catch (Exception e) { e.printStackTrace(); if (conn != null) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } throw new ApplicationException(e.getMessage(), e); } finally { if (dbc != null) try { dbc.close(); } catch (Exception e) { e.printStackTrace(); } } }
|
11
|
Code Sample 1:
protected Boolean lancerincident(long idbloc, String Etatbloc, java.util.GregorianCalendar datebloc, long idServeur, String niveau, String message) { String codeerr; Boolean retour = false; Boolean SauvegardeEtatAutocommit; int etat; acgtools_core.AcgIO.SortieLog(new Date() + " - Appel de la fonction Lancer incident"); Statement statement = null; ResultSet resultat = null; String RequeteSQL = ""; acgtools_core.AcgIO.SortieLog(new Date() + " - nouvel incident pour le bloc : " + acgtools_core.AcgIO.RetourneDate(datebloc)); try { this.con = db.OpenConnection(); SauvegardeEtatAutocommit = this.con.getAutoCommit(); this.con.setAutoCommit(false); if (idbloc == 0) { idbloc = this.CreationBloc(idServeur); if (idbloc == 0) { retour = false; acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la création du bloc"); this.con.rollback(); this.con.close(); return false; } } acgtools_core.AcgIO.SortieLog(new Date() + " - bloc : " + idbloc); etat = this.ChargerEtatServeur(idbloc, datebloc); if (etat != 2) { statement = con.createStatement(); acgtools_core.AcgIO.SortieLog(new Date() + " - Etat chargé"); RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job ='" + idbloc + "' " + "AND incref_err_numer NOT IN " + "(SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_err_etat='c') " + "AND incref_err_numer NOT IN " + "(SELECT incenc_err_numer FROM tbl_incident_encours " + "WHERE incenc_err_etat='c') ;"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (!resultat.next()) { resultat.close(); RequeteSQL = "INSERT INTO tbl_incident_ref " + "(incref_cde_job,incref_err_date,incref_err_etat,incref_niv_crimd,incref_err_msg,incref_err_srvnm)" + "VALUES ('" + idbloc + "','" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','" + Etatbloc + "','" + niveau + "','" + message + "','" + idServeur + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job = '" + idbloc + "' " + "AND incref_err_srvnm = '" + idServeur + "' " + "AND incref_err_date = '" + acgtools_core.AcgIO.RetourneDate(datebloc) + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (resultat.next()) { codeerr = resultat.getString("incref_err_numer"); resultat.close(); RequeteSQL = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + message + "','" + niveau + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); acgtools_core.AcgIO.SortieLog(new Date() + " - Incident inséré dans la base de données"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, acgtools_core.AcgIO.RetourneDate(datebloc), message); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'historique"); this.CreerHistorique(codeerr); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(true); retour = true; } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Problème d'insertion du nouvel incident dans la base"); retour = false; } } else { codeerr = resultat.getString("incref_err_numer"); acgtools_core.AcgIO.SortieLog(new Date() + " - Numéro de l'erreur trouvé. Numéro =" + codeerr); RequeteSQL = "SELECT incenc_err_etat FROM tbl_incident_encours " + "WHERE incenc_err_numer='" + codeerr + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (!resultat.next()) { resultat.close(); acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident."); String RequeteSQLInsert = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + "Incident non cloturé - " + message + "','" + niveau + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQLInsert); statement.execute(RequeteSQLInsert); resultat = statement.executeQuery(RequeteSQL); } else { resultat = statement.executeQuery(RequeteSQL); acgtools_core.AcgIO.SortieLog(new Date() + " - Incident correctement positionné dans encours"); } if (resultat.next()) { switch(Etatbloc.charAt(0)) { case 'c': { acgtools_core.AcgIO.SortieLog(new Date() + " - Cloture de l'incident."); RequeteSQL = "UPDATE tbl_incident_ref SET incref_err_etat='c'" + "WHERE incref_err_numer='" + codeerr + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); this.UpdateEnCours(codeerr, "c", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } case 'm': { this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } default: { this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, ""); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } } } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident."); retour = false; } } } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Systeme en maintenance, pas de remontée d'incidents."); retour = false; } } catch (ClassNotFoundException ex) { acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications."); con.rollback(); acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la connexion."); acgtools_core.AcgIO.SortieLog(ex.getMessage()); retour = false; } catch (SQLException ex) { acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications."); con.rollback(); acgtools_core.AcgIO.SortieLog(ex.getMessage()); acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la requète SQL :"); acgtools_core.AcgIO.SortieLog(RequeteSQL); retour = false; } finally { try { if (statement != null) { statement.close(); } if (retour) { con.commit(); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : succès"); } else { con.rollback(); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : echec"); } if (con != null) { con.close(); } } catch (Exception e) { acgtools_core.AcgIO.SortieLog(new Date() + "Problème lors de la fermeture de la connection à la base de données"); } return retour; } }
Code Sample 2:
public void cleanup(long timeout) throws PersisterException { long threshold = System.currentTimeMillis() - timeout; Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("delete from " + _table_name + " where " + _ts_col + " < ?"); ps.setLong(1, threshold); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to cleanup timed out objects: ", th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
|
11
|
Code Sample 1:
private void copyFile(File f) throws IOException { File newFile = new File(destdir + "/" + f.getName()); newFile.createNewFile(); FileInputStream fin = new FileInputStream(f); FileOutputStream fout = new FileOutputStream(newFile); int c; while ((c = fin.read()) != -1) fout.write(c); fin.close(); fout.close(); }
Code Sample 2:
public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
|
11
|
Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public static boolean writeFile(HttpServletResponse resp, File reqFile) { boolean retVal = false; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(reqFile)); IOUtils.copy(in, resp.getOutputStream()); logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath()); } catch (FileNotFoundException e) { logger.error("Resource not found: " + reqFile.getAbsolutePath()); } catch (IOException e) { logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()), e); } finally { IOUtils.closeQuietly(in); } return retVal; }
|
11
|
Code Sample 1:
public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } }
Code Sample 2:
private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
|
11
|
Code Sample 1:
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } }
Code Sample 2:
@org.junit.Test public void testReadWrite() throws Exception { final String reference = "testString"; final Reader reader = new StringReader(reference); final StringWriter osString = new StringWriter(); final Reader teeStream = new TeeReaderWriter(reader, osString); IOUtils.copy(teeStream, new NullWriter()); teeStream.close(); osString.toString(); }
|
11
|
Code Sample 1:
public void overwriteTest() throws Exception { SRBAccount srbAccount = new SRBAccount("srb1.ngs.rl.ac.uk", 5544, this.cred); srbAccount.setDefaultStorageResource("ral-ngs1"); SRBFileSystem client = new SRBFileSystem(srbAccount); client.setFirewallPorts(64000, 65000); String home = client.getHomeDirectory(); System.out.println("home: " + home); SRBFile file = new SRBFile(client, home + "/test.txt"); assertTrue(file.exists()); File filefrom = new File("/tmp/from.txt"); assertTrue(filefrom.exists()); SRBFileOutputStream to = null; InputStream from = null; try { to = new SRBFileOutputStream((SRBFile) file); from = new FileInputStream(filefrom); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } to.flush(); } finally { try { if (to != null) { to.close(); } } catch (Exception ex) { } try { if (from != null) { from.close(); } } catch (Exception ex) { } } }
Code Sample 2:
public void copyFile(File in, File out) throws Exception { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
|
00
|
Code Sample 1:
public void echo(HttpRequest request, HttpResponse response) throws IOException { InputStream in = request.getInputStream(); if ("gzip".equals(request.getField("Content-Encoding"))) { in = new GZIPInputStream(in); } IOUtils.copy(in, response.getOutputStream()); }
Code Sample 2:
public static String getHash(String key) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); return new BigInteger(digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return key; } }
|
00
|
Code Sample 1:
public static void main(String[] args) { try { FTPClient p = new FTPClient(); p.connect("url"); p.login("login", "pass"); int sendCommand = p.sendCommand("SYST"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PWD"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("NOOP"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PASV"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); p.changeWorkingDirectory("/"); try { printDir(p, "/"); } catch (Exception e) { e.printStackTrace(); } p.logout(); p.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void copy(File sourceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public HashMap parseFile(File newfile) throws IOException { String s; String[] tokens; int nvalues = 0; double num1, num2, num3; boolean baddata = false; URL url = newfile.toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); HashMap data = new HashMap(); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; if (nvalues == 2) { data.put(new String(tokens[0]), new Double(Double.parseDouble(tokens[1]))); } else { System.out.println("Sorry, trouble reading reference file."); } } return data; }
Code Sample 2:
public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public Ontology open(String resource_name) { Ontology ontology = null; try { URL url = null; if (resource_name.startsWith("jar")) url = new URL(resource_name); else { ClassLoader cl = this.getClass().getClassLoader(); url = cl.getResource(resource_name); } InputStream input_stream; if (url != null) { JarURLConnection jc = (JarURLConnection) url.openConnection(); input_stream = jc.getInputStream(); } else input_stream = new FileInputStream(resource_name); ObjectInputStream ois = new ObjectInputStream(input_stream); ontology = (Ontology) ois.readObject(); ois.close(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return ontology; }
Code Sample 2:
public void constructFundamentalView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { FundView = new BufferedWriter(new FileWriter("InfoFiles/FundamentalView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; FundView.write(className); FundView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; FundView.write("StartOfMethod"); FundView.newLine(); FundView.write(methodName); FundView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(readArray[i + j]); FundView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(writeArray[i + j]); FundView.newLine(); } } } } } FundView.write("EndOfMethod"); FundView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { FundView.write("EndOfClass"); FundView.newLine(); classWritten = false; } } PC.close(); FundView.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("usage: PutFromFile [properties file] [file with pmpxml]"); throw new IllegalArgumentException("Wrong number of arguments"); } Reader is = new FileReader(args[1]); char[] b = new char[1024]; StringBuffer sb = new StringBuffer(); int n; while ((n = is.read(b)) > 0) { sb.append(b, 0, n); } String test = sb.toString(); System.out.println(test); String strurl = args[0]; String data = "verb=PutRecord&xml=" + URLEncoder.encode(test, "UTF-8"); URL url = new URL(strurl); 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; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); }
Code Sample 2:
public static void main(String[] args) throws Exception { BufferedImage image = ImageIO.read(BitmapFont.class.getResource("Candara-38-Bold.png")); URL url = BitmapFontData.class.getResource("Candara-38-Bold.fnt"); BitmapFontData bitmapFontData = new BitmapFontData(url.openStream(), true); BitmapFont font = new BitmapFont(bitmapFontData, true); font.drawMultiLine("Hello world\nthis is a\ntest!!!", 100, 100); VertexData vertexData = font.createVertexData(); Display.setDisplayMode(new DisplayMode(640, 480)); Display.create(); RenderPass renderPass = new RenderPass(); renderPass.setClearMask(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); renderPass.setClearColor(new Color4f(0.3f, 0.4f, 0.5f, 1f)); renderPass.setView(View.createOrtho(0, 640, 0, 480, -1000, 1000)); ByteBuffer[][] pixels = { { TextureLoader.getImageData(image) } }; Texture texture = new Texture(TextureType.TEXTURE_2D, 4, image.getWidth(), image.getHeight(), 0, Format.BGRA, pixels, false, false); Shape shape = new Shape(vertexData); shape.getState().setUnit(0, new Unit(texture)); shape.getState().setBlendEnabled(true); shape.getState().setBlendSrcFunc(BlendSrcFunc.SRC_ALPHA); shape.getState().setBlendDstFunc(BlendDstFunc.ONE_MINUS_SRC_ALPHA); renderPass.getRootNode().addShape(shape); Renderer renderer = new Renderer(new SceneGraph(renderPass)); while (!Display.isCloseRequested()) { renderer.render(); Display.update(); } Display.destroy(); }
|
00
|
Code Sample 1:
public void doActionxxx() { try { System.out.println("app: ggc"); String server_name = "http://192.168.4.3:8080/"; server_name = server_name.trim(); if (server_name.length() == 0) { server_name = "http://www.atech-software.com/"; } else { if (!server_name.startsWith("http://")) server_name = "http://" + server_name; if (!server_name.endsWith("/")) server_name = server_name + "/"; } URL url = new URL(server_name + "ATechUpdateGetFile?" + "" + "file_id=1" + "&" + "version_requested=1"); InputStream is = url.openStream(); RandomAccessFile raf = new RandomAccessFile("/home/andy/test.jpg", "rw"); ArrayList<Integer> list = new ArrayList<Integer>(); float size = 671200; long current_size = 0; System.out.println("File size: " + is.available()); byte[] array = new byte[1024]; while (is.available() > 0) { if (is.available() < 1024) { array = new byte[is.available()]; } is.read(array); raf.write(array); current_size += array.length; System.out.println("Progress: " + ((current_size / size) * 100)); } System.out.println("Size Arr: " + list.size()); CheckSumUtility csu = new CheckSumUtility(); System.out.println("Checksum: " + csu.getChecksumValue("/home/andy/test.jpg")); } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
|
00
|
Code Sample 1:
public boolean copy(Class<?> subCls, String subCol, long id) { boolean bool = false; this.result = null; Connection conn = null; Object vo = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); PojoParser parser = PojoParser.getInstances(); String sql = SqlUtil.getInsertSql(this.getCls()); vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id); String pk = parser.getPriamryKey(cls); this.getCls().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 }); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, vo); ps.executeUpdate(); ps.close(); long key = this.id; parser = PojoParser.getInstances(); sql = SqlUtil.getInsertSql(subCls); Class<?> clses = this.cls; this.cls = subCls; ps = conn.prepareStatement("select * from " + parser.getTableName(subCls) + " where " + subCol + "=" + id); this.assembleObjToList(ps); ps = conn.prepareStatement(sql); ids = new long[orgList.size()]; Method m = subCls.getMethod("set" + SqlUtil.getFieldName(subCol), new Class[] { long.class }); for (int i = 0; i < orgList.size(); ++i) { Object obj = orgList.get(i); subCls.getMethod("set" + SqlUtil.getFieldName(parser.getPriamryKey(subCls)), new Class[] { long.class }).invoke(obj, new Object[] { 0 }); m.invoke(obj, new Object[] { key }); setPsParams(ps, obj); ps.addBatch(); if ((i % 100) == 0) ps.executeBatch(); ids[i] = this.id; } ps.executeBatch(); ps.close(); conn.commit(); this.cls = clses; this.id = key; bool = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { ex.printStackTrace(); } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; }
Code Sample 2:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
|
00
|
Code Sample 1:
@Override public String fetchURL(String urlString) throws ServiceException { try { URL url = new URL(urlString); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String content = ""; String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); return content; } catch (MalformedURLException e) { throw new ServiceException(e.getMessage()); } catch (IOException e) { throw new ServiceException(e.getMessage()); } }
Code Sample 2:
public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } }
|
00
|
Code Sample 1:
public DicomReader(URL url) throws java.io.IOException { final URLConnection u = url.openConnection(); final int size = u.getContentLength(); final byte[] array = new byte[size]; int bytes_read = 0; final DataInputStream in = new DataInputStream(u.getInputStream()); while (bytes_read < size) { bytes_read += in.read(array, bytes_read, size - bytes_read); } in.close(); this.dHR = new DicomHeaderReader(array); h = dHR.getRows(); w = dHR.getColumns(); highBit = dHR.getHighBit(); bitsStored = dHR.getBitStored(); bitsAllocated = dHR.getBitAllocated(); n = (bitsAllocated / 8); signed = (dHR.getPixelRepresentation() == 1); this.pixData = dHR.getPixels(); ignoreNegValues = true; samplesPerPixel = dHR.getSamplesPerPixel(); numberOfFrames = dHR.getNumberOfFrames(); dbg("Number of Frames " + numberOfFrames); }
Code Sample 2:
public static String md5(String value) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); try { messageDigest.update(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { messageDigest.update(value.getBytes()); } byte[] bytes = messageDigest.digest(); return byteArrayToHexString(bytes); }
|
11
|
Code Sample 1:
public void testExecute() throws Exception { LocalWorker worker = new JTidyWorker(); URL url = new URL("http://www.nature.com/index.html"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = in.readLine()) != null) { sb.append(str); sb.append(LINE_ENDING); } in.close(); Map inputMap = new HashMap(); DataThingAdapter inAdapter = new DataThingAdapter(inputMap); inAdapter.putString("inputHtml", sb.toString()); Map outputMap = worker.execute(inputMap); DataThingAdapter outAdapter = new DataThingAdapter(outputMap); assertNotNull("The outputMap was null", outputMap); String results = outAdapter.getString("results"); assertFalse("The results were empty", results.equals("")); assertNotNull("The results were null", results); }
Code Sample 2:
private void readFromFile1() throws DException { URL url1 = null; if (url == null) { url = getClass().getResource("/com/daffodilwoods/daffodildb/utils/parser/parser.schema"); try { url = new URL(url.getProtocol() + ":" + url.getPath().substring(0, url.getPath().indexOf("/parser.schema"))); } catch (MalformedURLException ex2) { ex2.printStackTrace(); throw new DException("DSE0", new Object[] { ex2 }); } try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } if (url1 == null) { throw new DException("DSE0", new Object[] { "Parser.schema file is missing in classpath." }); } } else { try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } } ArrayList arr1 = null; StringBuffer rule = null; try { LineNumberReader raf = new LineNumberReader(new BufferedReader(new InputStreamReader(url1.openStream()))); arr1 = new ArrayList(); rule = new StringBuffer(""); while (true) { String str1 = raf.readLine(); if (str1 == null) { break; } String str = str1.trim(); if (str.length() == 0) { if (rule.length() > 0) { arr1.add(rule.toString()); } rule = new StringBuffer(""); } else { rule.append(" ").append(str); } } raf.close(); } catch (IOException ex1) { ex1.printStackTrace(); throw new DException("DSE0", new Object[] { ex1 }); } if (rule.length() > 0) arr1.add(rule.toString()); for (int i = 0; i < arr1.size(); i++) { String str = (String) arr1.get(i); int index = str.indexOf("::="); if (index == -1) { P.pln("Error " + str); throw new DException("DSE0", new Object[] { "Rule is missing from parser.schema" }); } String key = str.substring(0, index).trim(); String value = str.substring(index + 3).trim(); Object o = fileEntries.put(key, value); if (o != null) { new Exception("Duplicate Defination for Rule [" + key + "] Value [" + value + "] Is Replaced By [" + o + "]").printStackTrace(); } } }
|
00
|
Code Sample 1:
public static void readFile(FOUserAgent ua, String uri, Writer output, String encoding) throws IOException { InputStream in = getURLInputStream(ua, uri); try { StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, encoding); } finally { IOUtils.closeQuietly(in); } }
Code Sample 2:
public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } }
|
00
|
Code Sample 1:
public void run() throws Exception { logger.debug("#run enter"); logger.debug("#run orderId = " + orderId); ResultSet rs = null; PreparedStatement ps = null; try { connection.setAutoCommit(false); ps = connection.prepareStatement(SQL_SELECT_ORDER_LINE); ps.setInt(1, orderId); rs = ps.executeQuery(); DeleteOrderLineAction action = new DeleteOrderLineAction(); while (rs.next()) { Integer lineId = rs.getInt("ID"); Integer itemId = rs.getInt("ITEM_ID"); Integer quantity = rs.getInt("QUANTITY"); action.execute(connection, lineId, itemId, quantity); } rs.close(); ps.close(); ps = connection.prepareStatement(SQL_DELETE_ORDER); ps.setInt(1, orderId); ps.executeUpdate(); ps.close(); logger.info("#run order delete OK"); connection.commit(); } catch (SQLException ex) { logger.error("SQLException", ex); connection.rollback(); throw new Exception("Не удалось удалить заказ. Ошибка : " + ex.getMessage()); } finally { connection.setAutoCommit(true); } logger.debug("#run exit"); }
Code Sample 2:
public Object execute(ExecutionEvent event) throws ExecutionException { final List<InformationUnit> informationUnitsFromExecutionEvent = InformationHandlerUtil.getInformationUnitsFromExecutionEvent(event); Shell activeShell = HandlerUtil.getActiveShell(event); DirectoryDialog fd = new DirectoryDialog(activeShell, SWT.SAVE); String section = Activator.getDefault().getDialogSettings().get("lastExportSection"); fd.setFilterPath(section); final String open = fd.open(); if (open != null) { Activator.getDefault().getDialogSettings().put("lastExportSection", open); CancelableRunnable runnable = new CancelableRunnable() { @Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; } }; ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(activeShell); try { progressMonitorDialog.run(true, true, runnable); } catch (InvocationTargetException e) { if (e.getCause() instanceof CoreException) { ErrorDialog.openError(activeShell, Messages.SaveFileOnDiskHandler_ErrorSaving2, Messages.SaveFileOnDiskHandler_ErrorSaving2, ((CoreException) e.getCause()).getStatus()); } else { ErrorDialog.openError(activeShell, Messages.SaveFileOnDiskHandler_ErrorSaving2, Messages.SaveFileOnDiskHandler_ErrorSaving2, StatusCreator.newStatus(Messages.SaveFileOnDiskHandler_ErrorSaving3, e)); } } catch (InterruptedException e) { } } return null; }
|
00
|
Code Sample 1:
public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException { if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength); if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'"); HashCash result = new HashCash(); MessageDigest md = MessageDigest.getInstance("SHA1"); result.myResource = resource; result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions); result.myDate = date; result.myVersion = version; String prefix; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); switch(version) { case 0: prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); md.reset(); md.update(result.myToken.getBytes()); result.myValue = numberOfLeadingZeros(md.digest()); break; case 1: result.myValue = value; prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); break; default: throw new IllegalArgumentException("Only supported versions are 0 and 1"); } return result; }
Code Sample 2:
public void run() { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Checking for updates at " + checkUrl); } URL url = new URL(checkUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String s = reader.readLine(); while (s != null) { content.append(s); s = reader.readLine(); } LOGGER.info("update-available", content.toString()); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("No update available (Response code " + connection.getResponseCode() + ")"); } } catch (Throwable e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Update check failed", e); } } }
|
00
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public TestReport runImpl() throws Exception { String parser = XMLResourceDescriptor.getXMLParserClassName(); DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parser); File f = (new File(testFileName)); URL url = f.toURL(); Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream()); Element e = doc.getElementById(targetId); if (e == null) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_GET_ELEMENT_BY_ID_FAILED); report.addDescriptionEntry(ENTRY_KEY_ID, targetId); report.setPassed(false); return report; } Document otherDocument = df.createDocument(null, rootTag, url.toString(), url.openStream()); DocumentFragment docFrag = otherDocument.createDocumentFragment(); try { docFrag.appendChild(doc.getDocumentElement()); } catch (DOMException ex) { return reportSuccess(); } DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_EXCEPTION_NOT_THROWN); report.setPassed(false); return report; }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void copyFile(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:
private void testConnection(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); try { con.connect(); assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); } finally { con.disconnect(); } }
Code Sample 2:
public static final void copy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
|
11
|
Code Sample 1:
public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } }
Code Sample 2:
private void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
Code Sample 2:
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
|
00
|
Code Sample 1:
public static String getPublicIP(Boolean proxy) { String IP = null; if (!proxy) { try { URL url = new URL(XMLConfigParser.urlHost + "getPublicIp.php"); HttpURLConnection Conn = (HttpURLConnection) url.openConnection(); InputStream InStream = Conn.getInputStream(); InputStreamReader Isr = new java.io.InputStreamReader(InStream); BufferedReader Br = new java.io.BufferedReader(Isr); IP = Br.readLine(); NetworkLog.logMsg(NetworkLog.LOG_INFO, Tools.class, "Your public IP address is " + IP); } catch (Exception e) { Log.error(Tools.class, e.getMessage()); } } else { XMLConfigParser.readProxyConfiguration(); System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyHost", XMLConfigParser.proxyHost); System.getProperties().put("proxyPort", XMLConfigParser.proxyPort); URL url; try { url = new URL(XMLConfigParser.urlHost + "getPublicIp.php"); URLConnection urlConn = url.openConnection(); String password = XMLConfigParser.proxyUsername + ":" + XMLConfigParser.proxyPassword; String encoded = Base64.encodeBase64String(password.getBytes()); urlConn.setRequestProperty("Proxy-Authorization", encoded); InputStream InStream = urlConn.getInputStream(); InputStreamReader Isr = new java.io.InputStreamReader(InStream); BufferedReader Br = new java.io.BufferedReader(Isr); IP = Br.readLine(); NetworkLog.logMsg(NetworkLog.LOG_INFO, Tools.class, "Your public IP address is " + IP); } catch (MalformedURLException e) { Log.error(Tools.class, e.getMessage()); } catch (IOException e) { Log.error(Tools.class, e.getMessage()); } } return IP; }
Code Sample 2:
@Override public void run() { YouTubeFeedParserHandler parserHandler = new YouTubeFeedParserHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); try { URL url = new URL(m_YouTubeFeedUrl); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(parserHandler); InputStream is = url.openStream(); InputSource input = new InputSource(is); xr.parse(input); } catch (MalformedURLException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); }
Code Sample 2:
@Override public void handler(Map<String, Match> result, TargetPage target) { List<String> lines = new LinkedList<String>(); List<String> page = new LinkedList<String>(); try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { page.add(line); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } try { result.put("27 svk par fix", MatchEventFactory.getFix27()); result.put("41 svk ita fix", MatchEventFactory.getFix41()); result.put("01 rsa mex", MatchEventFactory.get01()); result.put("02 uru fra", MatchEventFactory.get02()); result.put("04 kor gre", MatchEventFactory.get04()); result.put("03 arg ngr", MatchEventFactory.get03()); result.put("05 eng usa", MatchEventFactory.get05()); result.put("06 alg slo", MatchEventFactory.get06()); result.put("08 scg gha", MatchEventFactory.get08()); result.put("07 ger aus", MatchEventFactory.get07()); result.put("09 end den", MatchEventFactory.get09()); result.put("10 jpn cmr", MatchEventFactory.get10()); result.put("11 ita par", MatchEventFactory.get11()); result.put("12 nzl svk", MatchEventFactory.get12()); result.put("13 civ por", MatchEventFactory.get13()); result.put("14 bra prk", MatchEventFactory.get14()); result.put("15 hon chi", MatchEventFactory.get15()); result.put("16 esp sui", MatchEventFactory.get16()); result.put("17 rsa uru", MatchEventFactory.get17()); result.put("20 arg kor", MatchEventFactory.get20()); result.put("19 gre ngr", MatchEventFactory.get19()); result.put("18 fra mex", MatchEventFactory.get18()); result.put("21 ger scg", MatchEventFactory.get21()); result.put("22 slo usa", MatchEventFactory.get22()); result.put("23 eng alg", MatchEventFactory.get23()); result.put("25 end jpn", MatchEventFactory.get25()); result.put("24 gha aus", MatchEventFactory.get24()); result.put("26 cmr den", MatchEventFactory.get26()); result.put("27 slo par", MatchEventFactory.get27()); result.put("28 ita nzl", MatchEventFactory.get28()); result.put("29 bra civ", MatchEventFactory.get29()); result.put("30 por prk", MatchEventFactory.get30()); result.put("31 chi sui", MatchEventFactory.get31()); result.put("32 esp hon", MatchEventFactory.get32()); result.put("34 fra rsa", MatchEventFactory.get34()); result.put("33 mex uru", MatchEventFactory.get33()); result.put("35 ngr kor", MatchEventFactory.get35()); result.put("36 gre arg", MatchEventFactory.get36()); result.put("38 usa alg", MatchEventFactory.get38()); result.put("37 slo eng", MatchEventFactory.get37()); result.put("39 gha ger", MatchEventFactory.get39()); result.put("40 aus scg", MatchEventFactory.get40()); result.put("42 par nzl", MatchEventFactory.get42()); result.put("41 slo ita", MatchEventFactory.get41()); result.put("44 cmr ned", MatchEventFactory.get44()); result.put("43 den jpn", MatchEventFactory.get43()); result.put("45 por bra", MatchEventFactory.get45()); result.put("46 prk civ", MatchEventFactory.get46()); result.put("47 chi esp", MatchEventFactory.get47()); result.put("48 sui hon", MatchEventFactory.get48()); result.put("49 uru kor", MatchEventFactory.get49Team()); result.put("50 usa gha", MatchEventFactory.get50Team()); result.put("51 ger eng", MatchEventFactory.get51Team()); result.put("52 arg mex", MatchEventFactory.get52Team()); result.put("53 ned svk", MatchEventFactory.get53Team()); result.put("54 bra chi", MatchEventFactory.get54Team()); result.put("55 par jpn", MatchEventFactory.get55Team()); result.put("56 esp por", MatchEventFactory.get56Team()); result.put("57 ned bra", MatchEventFactory.get57Team()); result.put("58 uru gha", MatchEventFactory.get58Team()); result.put("59 arg ger", MatchEventFactory.get59Team()); result.put("49", MatchEventFactory.get49()); result.put("50", MatchEventFactory.get50()); result.put("51", MatchEventFactory.get51()); result.put("52", MatchEventFactory.get52()); result.put("53", MatchEventFactory.get53()); result.put("54", MatchEventFactory.get54()); this.stage2MatchHandler("318295", "55", "2010-06-29 22:30", result); this.stage2MatchHandler("318296", "56", "2010-06-30 02:30", result); this.stage2MatchHandler("318297", "57", "2010-07-02 22:00", result); this.stage2MatchHandler("318298", "58", "2010-07-03 02:30", result); this.stage2MatchHandler("318299", "59", "2010-07-03 22:00", result); this.stage2MatchHandler("318300", "60", "2010-07-04 02:30", result); this.stage2MatchHandler("318301", "61", "2010-07-07 02:30", result); this.stage2MatchHandler("318302", "62", "2010-07-08 02:30", result); this.stage2MatchHandler("318303", "63", "2010-07-11 02:30", result); this.stage2MatchHandler("318304", "64", "2010-07-12 02:30", result); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { FileChannel fc = new FileOutputStream("src/com/aaron/nio/data.txt").getChannel(); fc.write(ByteBuffer.wrap("dfsdf ".getBytes())); fc.close(); fc = new RandomAccessFile("src/com/aaron/nio/data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("中文的 ".getBytes())); fc.close(); fc = new FileInputStream("src/com/aaron/nio/data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(1024); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { System.out.print(buff.getChar()); } fc.close(); }
Code Sample 2:
private void downloadThread() { int c; status = false; try { URLConnection urlc = resource.url.openConnection(); File f = resource.createFile(); boolean resume = false; resource.resetBytesDown(); if (f.exists()) { if (f.lastModified() > resource.date.getTime()) { if ((resource.getFileSize() == f.length())) { status = true; return; } else { urlc.setRequestProperty("Range", "bytes=" + f.length() + "-"); resume = true; resource.incrementBytesDown(f.length()); System.out.println("Resume download"); System.out.println("file length: " + f.length()); } } } urlc.connect(); bin = new BufferedInputStream(urlc.getInputStream()); file_out = new FileOutputStream(f.getPath(), resume); while (life) { if (bin.available() > 0) { c = bin.read(); if (c == -1) { break; } file_out.write(c); if (resource.incrementBytesDown()) { break; } else { continue; } } sleep(WAIT_FOR_A_BYTE_TIME); } file_out.flush(); status = true; } catch (IOException e) { System.out.println("excepcion cpoy file"); } catch (InterruptedException e) { System.out.println("InterruptException download"); System.out.println(e); } }
|
11
|
Code Sample 1:
private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
Code Sample 2:
public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.exit(-1); } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); }
|
00
|
Code Sample 1:
public static void copyFolderStucture(String strPath, String dstPath) throws IOException { Constants.iLog.LogInfoLine("copying " + strPath); File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFolderStucture(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
Code Sample 2:
public APIResponse update(Variable variable) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/variable/update").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(variable, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Update Variable Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
|
11
|
Code Sample 1:
private long getNextHighValue() throws Exception { Connection con = null; PreparedStatement psGetHighValue = null; PreparedStatement psUpdateHighValue = null; ResultSet rs = null; long high = -1L; int isolation = -1; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); psGetHighValue = con.prepareStatement(strGetHighValue); psGetHighValue.setString(1, this.name); for (rs = psGetHighValue.executeQuery(); rs.next(); ) { high = rs.getLong("high"); } psUpdateHighValue = con.prepareStatement(strUpdateHighValue); psUpdateHighValue.setLong(1, high + 1L); psUpdateHighValue.setString(2, this.name); psUpdateHighValue.executeUpdate(); } catch (SQLException e) { if (con != null) { con.rollback(); } throw e; } finally { if (psUpdateHighValue != null) { psUpdateHighValue.close(); } close(dbo, psGetHighValue, rs); } return high; }
Code Sample 2:
public static boolean insereMidia(final Connection con, Midia mid, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodMidia(con, mid); GeraID.gerarCodDescricao(con, desc); String titulo = mid.getTitulo().replaceAll("['\"]", ""); String coment = mid.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO midia VALUES(" + mid.getCodigo() + ", '" + titulo + "', '" + coment + "','" + mid.getUrl() + "', '" + mid.getTipo() + "', " + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO mid_aut VALUES(" + mid.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "MIDIA: Database error", JOptionPane.ERROR_MESSAGE); System.err.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getMessage()); } } }
|
11
|
Code Sample 1:
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); } }
Code Sample 2:
private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
|
11
|
Code Sample 1:
public static Vector getMetaKeywordsFromURL(String p_url) throws Exception { URL x_url = new URL(p_url); URLConnection x_conn = x_url.openConnection(); InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream()); BufferedReader x_reader = new BufferedReader(x_is_reader); String x_line = null; String x_lc_line = null; int x_body = -1; String x_keyword_list = null; int x_keywords = -1; String[] x_meta_keywords = null; while ((x_line = x_reader.readLine()) != null) { x_lc_line = x_line.toLowerCase(); x_keywords = x_lc_line.indexOf("<meta name=\"keywords\" content=\""); if (x_keywords != -1) { x_keywords = "<meta name=\"keywords\" content=\"".length(); x_keyword_list = x_line.substring(x_keywords, x_line.indexOf("\">", x_keywords)); x_keyword_list = x_keyword_list.replace(',', ' '); x_meta_keywords = Parser.extractWordsFromSpacedList(x_keyword_list); } x_body = x_lc_line.indexOf("<body"); if (x_body != -1) break; } Vector x_vector = new Vector(x_meta_keywords.length); for (int i = 0; i < x_meta_keywords.length; i++) x_vector.add(x_meta_keywords[i]); return x_vector; }
Code Sample 2:
public Function findFunction(String functionName) { String code = ""; UserFunction function = (UserFunction) getCachedFunction(functionName); if (function != null) return function; ErrorLogger.debugLine("MFileWebLoader: loading >" + functionName + ".m<"); try { URL url = new URL(codeBase, directory + "/" + functionName + ".m"); InputStream in = url.openStream(); BufferedReader inReader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = inReader.readLine()) != null) { code += line + "\n"; } inReader.close(); } catch (Exception e) { Errors.throwMathLibException("MFileWebLoader: m-file exception via web"); } ErrorLogger.debugLine("MFileWebLoader: code: begin \n" + code + "\ncode end"); FunctionParser funcParser = new FunctionParser(); function = funcParser.parseFunction(code); function.setName(functionName); cacheFunction(function); ErrorLogger.debugLine("MFileWebLoader: finished webloading >" + functionName + ".m<"); return function; }
|
11
|
Code Sample 1:
private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
@HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
|
11
|
Code Sample 1:
public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
Code Sample 2:
private static int ejecutaUpdate(String database, String SQL) throws Exception { int i = 0; DBConnectionManager dbm = null; Connection bd = null; try { dbm = DBConnectionManager.getInstance(); bd = dbm.getConnection(database); Statement st = bd.createStatement(); i = st.executeUpdate(SQL); bd.commit(); st.close(); dbm.freeConnection(database, bd); } catch (Exception e) { log.error("SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (bd == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { bd.rollback(); excep = new Exception("SQL Error: " + SQL + " error: " + e); dbm.freeConnection(database, bd); } throw excep; } return i; }
|
11
|
Code Sample 1:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
Code Sample 2:
public static void CreateBackupOfDataFile(String _src, String _dest) { try { File src = new File(_src); File dest = new File(_dest); if (new File(_src).exists()) { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
protected static String readUrl(URL url) throws IOException { BufferedReader in = null; StringBuffer buf = new StringBuffer(); try { in = new BufferedReader(new InputStreamReader(url.openStream())); final char[] charBuf = new char[1024]; int len = 0; while ((len = in.read(charBuf)) != -1) buf.append(charBuf, 0, len); } finally { if (in != null) in.close(); } return buf.toString(); }
Code Sample 2:
public void run() { if (withlinlyn == true) { try { xlin.erase(file); } catch (Exception e) { System.out.println("Error erasing"); } } else if (as_php) { try { URL url = new URL(http + "REM:" + pservname); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); System.out.println("Response from REMOVE:"); String s; while ((s = br.readLine()) != null) { System.out.println(s); } br.close(); } catch (Exception e) { System.out.println("Error erasing/php!"); } } try { InetAddress ia = InetAddress.getLocalHost(); ss = new ServerSocket(0, 50, ia); startserv = System.currentTimeMillis(); ss.setSoTimeout(0); String svname = ia.getHostAddress(); System.out.println(svname + ":sv"); String mssg = "<SERVER><IP>" + svname + "</IP><PORT>" + ss.getLocalPort() + "</PORT></SERVER>"; if (withlinlyn == true) { try { xlin.replace(file, mssg); System.out.println("mssg:" + mssg + ", sent"); } catch (Exception e) { System.out.println("Error posting address"); return; } } else if (as_php) { try { URL url = new URL(http + "ADD:" + svname + ":" + ss.getLocalPort() + ":" + pservname); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String s; while ((s = br.readLine()) != null) { response = response + s + System.getProperty("line.separator"); } br.close(); String resp = new xLineSplit().ssplit("REPLY", response); if (!resp.equalsIgnoreCase("ADDED")) { System.out.println("potential error posting via php:\nReponse was:\n" + response); } } catch (Exception e) { System.out.println("Error in posting php:" + e.toString()); } } xsl.regserver(svname, new String("" + ss.getLocalPort())); Socket server = null; listening = true; while (listening) { server = ss.accept(); if (server != null) { xsl.add(server); System.out.println("added connect"); } else { System.out.println("Received null socket"); } server = null; listening = control_listening; } finserv = System.currentTimeMillis(); long l = finserv - startserv; long m = l / 1000; System.err.println("Server socket has closed, time elapsed:" + m); System.out.println("Server socket has closed, time elapsed:" + m); } catch (Exception e) { System.out.println(e.toString()); } }
|
00
|
Code Sample 1:
private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0) outFile.write(buf, 0, read); inFile.close(); }
Code Sample 2:
@Override public String baiDuHotNews() { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://news.baidu.com/z/wise_topic_processor/wise_hotwords_list.php?bd_page_type=1&tn=wapnews_hotwords_list&type=1&index=1&pfr=3-11-bdindex-top-3--"); String hostNews = ""; try { HttpResponse response = client.execute(httpGet); HttpEntity httpEntity = response.getEntity(); BufferedReader buffer = new BufferedReader(new InputStreamReader(httpEntity.getContent())); String line = ""; boolean todayNewsExist = false, firstNewExist = false; int newsCount = -1; while ((line = buffer.readLine()) != null) { if (todayNewsExist || line.contains("<div class=\"news_title\">")) todayNewsExist = true; else continue; if (firstNewExist || line.contains("<div class=\"list-item\">")) { firstNewExist = true; newsCount++; } else continue; if (todayNewsExist && firstNewExist && (newsCount == 1)) { Pattern hrefPattern = Pattern.compile("<a.*>(.+?)</a>.*"); Matcher matcher = hrefPattern.matcher(line); if (matcher.find()) { hostNews = matcher.group(1); break; } else newsCount--; } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return hostNews; }
|
11
|
Code Sample 1:
public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } }
Code Sample 2:
public static String sendSoapMsg(String SOAPUrl, byte[] b, String SOAPAction) throws IOException { log.finest("HTTP REQUEST SIZE " + b.length); if (SOAPAction.startsWith("\"") == false) SOAPAction = "\"" + SOAPAction + "\""; URL url = new URL(SOAPUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty("Pragma", "no-cache"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); StringBuffer response = new StringBuffer(1024); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); log.finest("HTTP RESPONSE SIZE: " + response.length()); return response.toString(); }
|
00
|
Code Sample 1:
@Override public void doExecute(String[] args) { if (args.length != 2) { printUsage(); } else { int fileNo = 0; try { fileNo = Integer.parseInt(args[1]) - 1; } catch (NumberFormatException e) { printUsage(); return; } if (fileNo < 0) { printUsage(); return; } StorageFile[] files = (StorageFile[]) ctx.getRemoteDir().listFiles(); try { StorageFile file = files[fileNo]; File outFile = getOutFile(file); FileOutputStream out = new FileOutputStream(outFile); InputStream in = file.openStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); afterSave(outFile); if (outFile.exists()) { print("File written to: " + outFile.getAbsolutePath()); } } catch (IOException e) { printError("Failed to load file. " + e.getMessage()); } catch (Exception e) { printUsage(); return; } } }
Code Sample 2:
@Override public String compute_hash(String plaintext) { MessageDigest d; try { d = MessageDigest.getInstance(get_algorithm_name()); d.update(plaintext.getBytes()); byte[] hash = d.digest(); StringBuffer sb = new StringBuffer(); for (byte b : hash) sb.append(String.format("%02x", b)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public void create(Session session) { Connection conn = session.getConnection(this); Statement stat = null; StringBuilder out = new StringBuilder(256); Appendable sql = out; List<MetaTable> tables = new ArrayList<MetaTable>(); List<MetaColumn> newColumns = new ArrayList<MetaColumn>(); List<MetaColumn> foreignColumns = new ArrayList<MetaColumn>(); List<MetaIndex> indexes = new ArrayList<MetaIndex>(); boolean createSequenceTable = false; int tableTotalCount = getTableTotalCount(); try { stat = conn.createStatement(); if (isSequenceTableRequired()) { PreparedStatement ps = null; ResultSet rs = null; Throwable exception = null; String logMsg = ""; try { sql = getDialect().printSequenceCurrentValue(findFirstSequencer(), out); ps = conn.prepareStatement(sql.toString()); ps.setString(1, "-"); rs = ps.executeQuery(); } catch (Throwable e) { exception = e; } if (exception != null) { switch(MetaParams.ORM2DLL_POLICY.of(ormHandler.getParameters())) { case VALIDATE: throw new IllegalStateException(logMsg, exception); case CREATE_DDL: case CREATE_OR_UPDATE_DDL: createSequenceTable = true; } } if (LOGGER.isLoggable(Level.INFO)) { logMsg = "Table '" + SqlDialect.COMMON_SEQ_TABLE_NAME + "' {0} available on the database '{1}'."; logMsg = MessageFormat.format(logMsg, exception != null ? "is not" : "is", getId()); LOGGER.log(Level.INFO, logMsg); } try { if (exception != null) { conn.rollback(); } } finally { close(null, ps, rs, false); } } boolean ddlOnly = false; switch(MetaParams.ORM2DLL_POLICY.of(ormHandler.getParameters())) { case CREATE_DDL: ddlOnly = true; case CREATE_OR_UPDATE_DDL: case VALIDATE: boolean change = isModelChanged(conn, tables, newColumns, indexes); if (change && ddlOnly) { if (tables.size() < tableTotalCount) { return; } } break; case DO_NOTHING: default: return; } switch(MetaParams.CHECK_KEYWORDS.of(getParams())) { case WARNING: case EXCEPTION: Set<String> keywords = getDialect().getKeywordSet(conn); for (MetaTable table : tables) { if (table.isTable()) { checkKeyWord(MetaTable.NAME.of(table), table, keywords); for (MetaColumn column : MetaTable.COLUMNS.of(table)) { checkKeyWord(MetaColumn.NAME.of(column), table, keywords); } } } for (MetaColumn column : newColumns) { checkKeyWord(MetaColumn.NAME.of(column), column.getTable(), keywords); } for (MetaIndex index : indexes) { checkKeyWord(MetaIndex.NAME.of(index), MetaIndex.TABLE.of(index), keywords); } } if (tableTotalCount == tables.size()) for (String schema : getSchemas(tables)) { out.setLength(0); sql = getDialect().printCreateSchema(schema, out); if (isUsable(sql)) { try { stat.executeUpdate(sql.toString()); } catch (SQLException e) { LOGGER.log(Level.INFO, "{0}: {1}; {2}", new Object[] { e.getClass().getName(), sql.toString(), e.getMessage() }); conn.rollback(); } } } int tableCount = 0; for (MetaTable table : tables) { if (table.isTable()) { tableCount++; out.setLength(0); sql = getDialect().printTable(table, out); executeUpdate(sql, stat); foreignColumns.addAll(table.getForeignColumns()); } } for (MetaColumn column : newColumns) { out.setLength(0); sql = getDialect().printAlterTable(column, out); executeUpdate(sql, stat); if (column.isForeignKey()) { foreignColumns.add(column); } } for (MetaIndex index : indexes) { out.setLength(0); sql = getDialect().printIndex(index, out); executeUpdate(sql, stat); } for (MetaColumn column : foreignColumns) { if (column.isForeignKey()) { out.setLength(0); MetaTable table = MetaColumn.TABLE.of(column); sql = getDialect().printForeignKey(column, table, out); executeUpdate(sql, stat); } } if (createSequenceTable) { out.setLength(0); sql = getDialect().printSequenceTable(this, out); executeUpdate(sql, stat); } List<MetaTable> cTables = null; switch(MetaParams.COMMENT_POLICY.of(ormHandler.getParameters())) { case FOR_NEW_OBJECT: cTables = tables; break; case ALWAYS: case ON_ANY_CHANGE: cTables = TABLES.getList(this); break; case NEVER: cTables = Collections.emptyList(); break; default: throw new IllegalStateException("Unsupported parameter"); } if (!cTables.isEmpty()) { sql = out; createTableComments(cTables, stat, out); } conn.commit(); } catch (Throwable e) { try { conn.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Can't rollback DB" + getId(), ex); } throw new IllegalArgumentException(Session.SQL_ILLEGAL + sql, e); } }
Code Sample 2:
public static int copyFile(File src, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(src).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } return 1; }
|
00
|
Code Sample 1:
public static void translateTableMetaData(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table", nsDefinition); String filename = baseDir + "table.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + ".xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + ".json", baseDir + tableName + ".xsl"); }
Code Sample 2:
public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; }
|
11
|
Code Sample 1:
public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileOutputStream fos = new FileOutputStream(out); FileChannel outChannel = fos.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); fos.flush(); fos.close(); } }
|
00
|
Code Sample 1:
protected HttpURLConnection openConnection(final String url) throws IOException { final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("User-Agent", userAgent); connection.setRequestProperty("Accept", "application/xhtml+xml,application/xml,text/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Language", "ja,en-us;q=0.7,en;q=0.3"); connection.setRequestProperty("Accept-Encoding", "deflate"); connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("Authorization", "Basic ".concat(base64Encode((username.concat(":").concat(password)).getBytes("UTF-8")))); return connection; }
Code Sample 2:
private String protectMarkup(String content, String markupRegex, String replaceSource, String replaceTarget) { Matcher matcher = Pattern.compile(markupRegex, Pattern.MULTILINE | Pattern.DOTALL).matcher(content); StringBuffer result = new StringBuffer(); while (matcher.find()) { String protectedMarkup = matcher.group(); protectedMarkup = protectedMarkup.replaceAll(replaceSource, replaceTarget); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(protectedMarkup.getBytes("UTF-8")); String hash = bytesToHash(digest.digest()); matcher.appendReplacement(result, hash); c_protectionMap.put(hash, protectedMarkup); m_hashList.add(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } matcher.appendTail(result); return result.toString(); }
|
00
|
Code Sample 1:
public String hash(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { log.info("No sha-256 available"); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.fatal("sha-1 is not available", e); throw new RuntimeException("Couldn't get a hash algorithm from Java"); } } try { digest.reset(); digest.update((salt + password).getBytes("UTF-8")); byte hash[] = digest.digest(); return new String(Base64.encodeBase64(hash, false)); } catch (Throwable t) { throw new RuntimeException("Couldn't hash password"); } }
Code Sample 2:
public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
|
11
|
Code Sample 1:
public static void copyFile(File dst, File src, boolean append) throws FileNotFoundException, IOException { dst.createNewFile(); FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); long startAt = 0; if (append) startAt = out.size(); in.transferTo(startAt, in.size(), out); out.close(); in.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!"); }
|
11
|
Code Sample 1:
public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
Code Sample 2:
private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: destination file is unwriteable: " + toFileName); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
private void extractByParsingHtml(String refererURL, String requestURL) throws MalformedURLException, IOException { URL url = new URL(refererURL); InputStream is = url.openStream(); mRefererURL = refererURL; if (requestURL.startsWith("http://www.")) { mRequestURLWWW = requestURL; mRequestURL = "http://" + mRequestURLWWW.substring(11); } else { mRequestURL = requestURL; mRequestURLWWW = "http://www." + mRequestURL.substring(7); } Parser parser = (new HTMLEditorKit() { public Parser getParser() { return super.getParser(); } }).getParser(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } StringReader sr = new StringReader(sb.toString()); parser.parse(sr, new LinkbackCallback(), true); if (mStart != 0 && mEnd != 0 && mEnd > mStart) { mExcerpt = sb.toString().substring(mStart, mEnd); mExcerpt = Utilities.removeHTML(mExcerpt); if (mExcerpt.length() > mMaxExcerpt) { mExcerpt = mExcerpt.substring(0, mMaxExcerpt) + "..."; } } if (mTitle.startsWith(">") && mTitle.length() > 1) { mTitle = mTitle.substring(1); } }
Code Sample 2:
private Integer getInt(String sequence) throws NoSuchSequenceException { Connection conn = null; PreparedStatement read = null; PreparedStatement write = null; boolean success = false; try { conn = ds.getConnection(); conn.setTransactionIsolation(conn.TRANSACTION_REPEATABLE_READ); conn.setAutoCommit(false); read = conn.prepareStatement(SELECT_SQL); read.setString(1, sequence); ResultSet readRs = read.executeQuery(); if (!readRs.next()) { throw new NoSuchSequenceException(); } int currentSequenceId = readRs.getInt(1); int currentSequenceValue = readRs.getInt(2); Integer currentSequenceValueInteger = new Integer(currentSequenceValue); write = conn.prepareStatement(UPDATE_SQL); write.setInt(1, currentSequenceValue + 1); write.setInt(2, currentSequenceId); int rowsAffected = write.executeUpdate(); if (rowsAffected == 1) { success = true; return currentSequenceValueInteger; } else { logger.error("Something strange has happened. The row count was not 1, but was " + rowsAffected); return currentSequenceValueInteger; } } catch (SQLException sqle) { logger.error("Table based id generation failed : "); logger.error(sqle.getMessage()); return new Integer(0); } finally { if (read != null) { try { read.close(); } catch (Exception e) { } } if (write != null) { try { write.close(); } catch (Exception e) { } } if (conn != null) { try { if (success) { conn.commit(); } else { conn.rollback(); } conn.close(); } catch (Exception e) { } } } }
|
11
|
Code Sample 1:
private void initLogging() { File logging = new File(App.getHome(), "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties-setup"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); List<String> parts = header.getFilename().getSegments(); String filename; if (parts.size() > 0) filename = "dl-" + parts.get(parts.size() - 1); else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
|
11
|
Code Sample 1:
private void mergeOne(String level, char strand, String filename, Path outPath, FileSystem srcFS, FileSystem dstFS, Timer to) throws IOException { to.start(); final OutputStream outs = dstFS.create(new Path(outPath, filename)); final FileStatus[] parts = srcFS.globStatus(new Path(sorted ? getSortOutputDir(level, strand) : wrkDir, filename + "-[0-9][0-9][0-9][0-9][0-9][0-9]")); for (final FileStatus part : parts) { final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, getConf(), false); ins.close(); } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarize :: Merged %s%c in %d.%03d s.\n", level, strand, to.stopS(), to.fms()); }
Code Sample 2:
public void copyNIO(File in, File out) throws IOException { FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { inStream = new FileInputStream(in); outStream = new FileOutputStream(out); sourceChannel = inStream.getChannel(); destinationChannel = outStream.getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } }
|
00
|
Code Sample 1:
private String getHash(String string) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } String str = hexString.toString(); return str; }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
|
11
|
Code Sample 1:
private StringBuffer hashPassword(StringBuffer password, String mode) { MessageDigest m = null; StringBuffer hash = new StringBuffer(); try { m = MessageDigest.getInstance(mode); m.update(password.toString().getBytes("UTF8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] digest = m.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); hash.append(hex); } return hash; }
Code Sample 2:
@SuppressWarnings("unchecked") public ArrayList<GmailContact> getAllContacts() throws GmailException { String query = properties.getString("export_page"); query = query.replace("[RANDOM_INT]", "" + random.nextInt()); int statusCode = -1; GetMethod get = new GetMethod(query); if (log.isInfoEnabled()) log.info("getting all contacts ..."); try { statusCode = client.executeMethod(get); if (statusCode != 200) throw new GmailException("In contacts export page: Status code expected: 200 -> Status code returned: " + statusCode); } catch (HttpException e) { throw new GmailException("HttpException in contacts export page:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in contacts export page:" + e.getMessage()); } finally { get.releaseConnection(); } if (log.isTraceEnabled()) log.trace("accessing contacts export page successful..."); String query_post = properties.getString("outlook_export_page"); PostMethod post = new PostMethod(query_post); post.addRequestHeader("Accept-Encoding", "gzip,deflate"); post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.8"); NameValuePair[] data = { new NameValuePair("at", getCookie("GMAIL_AT")), new NameValuePair("ecf", "o"), new NameValuePair("ac", "Export Contacts") }; post.setRequestBody(data); if (log.isTraceEnabled()) log.trace("getting contacts csv file..."); try { statusCode = client.executeMethod(post); if (statusCode != 200) throw new GmailException("In csv file post: Status code expected: 200 -> Status code returned: " + statusCode); if (log.isTraceEnabled()) log.trace("Gmail: csv charset: " + post.getResponseCharSet()); GMAIL_OUTPUT_CHARSET = post.getResponseCharSet(); InputStreamReader isr = new InputStreamReader(new GZIPInputStream(post.getResponseBodyAsStream()), post.getResponseCharSet()); CSVReader reader = new CSVReader(isr); List csvEntries = reader.readAll(); reader.close(); ArrayList<GmailContact> contacts = new ArrayList<GmailContact>(); MessageDigest m = MessageDigest.getInstance("MD5"); if (log.isTraceEnabled()) log.trace("creating Gmail contacts..."); for (int i = 1; i < csvEntries.size(); i++) { GmailContact contact = new GmailContact(); String[] value = (String[]) csvEntries.get(i); for (int j = 0; j < value.length; j++) { switch(j) { case 0: contact.setName(value[j]); break; case 1: contact.setEmail(value[j]); if (contact.getName() == null) contact.setIdName(value[j]); else contact.setIdName(contact.getName() + value[j]); break; case 2: contact.setNotes(value[j]); break; case 3: contact.setEmail2(value[j]); break; case 4: contact.setEmail3(value[j]); break; case 5: contact.setMobilePhone(value[j]); break; case 6: contact.setPager(value[j]); break; case 7: contact.setCompany(value[j]); break; case 8: contact.setJobTitle(value[j]); break; case 9: contact.setHomePhone(value[j]); break; case 10: contact.setHomePhone2(value[j]); break; case 11: contact.setHomeFax(value[j]); break; case 12: contact.setHomeAddress(value[j]); break; case 13: contact.setBusinessPhone(value[j]); break; case 14: contact.setBusinessPhone2(value[j]); break; case 15: contact.setBusinessFax(value[j]); break; case 16: contact.setBusinessAddress(value[j]); break; case 17: contact.setOtherPhone(value[j]); break; case 18: contact.setOtherFax(value[j]); break; case 19: contact.setOtherAddress(value[j]); break; } } m.update(contact.toString().getBytes()); if (log.isTraceEnabled()) log.trace("setting Md5 Hash..."); contact.setMd5Hash(new BigInteger(m.digest()).toString()); contacts.add(contact); } if (log.isTraceEnabled()) log.trace("Mapping contacts uid..."); Collections.sort(contacts); ArrayList<GmailContact> idList = getAllContactsID(); for (int i = 0; i < idList.size(); i++) { contacts.get(i).setId(idList.get(i).getId()); } if (log.isInfoEnabled()) log.info("getting all contacts info successful..."); return contacts; } catch (HttpException e) { throw new GmailException("HttpException in csv file post:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in csv file post:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new GmailException("No such md5 algorithm " + e.getMessage()); } finally { post.releaseConnection(); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static boolean copyFile(String src, String dst) { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(new File(src)).getChannel(); outChannel = new FileOutputStream(new File(dst)).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (FileNotFoundException e) { e.printStackTrace(); MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst); return false; } catch (IOException e) { MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst); return false; } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } catch (IOException e) { MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst); return false; } } return true; }
|
11
|
Code Sample 1:
public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public SpreadSheetFrame(FileManager owner, File file, Delimiter delim) { super(owner, file.getPath()); JPanel pane = new JPanel(new BorderLayout()); super.contentPane.add(pane); this.tableModel = new BigTableModel(file, delim); this.table = new JTable(tableModel); this.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.tableModel.setTable(this.table); pane.add(new JScrollPane(this.table)); addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { tableModel.close(); } }); JMenu menu = new JMenu("Tools"); getJMenuBar().add(menu); menu.add(new AbstractAction("NCBI") { @Override public void actionPerformed(ActionEvent e) { try { Pattern delim = Pattern.compile("[ ]"); BufferedReader r = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("/home/lindenb/jeter.txt.gz")))); String line = null; URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("db=snp&retmode=xml"); while ((line = r.readLine()) != null) { String tokens[] = delim.split(line, 2); if (!tokens[0].startsWith("rs")) continue; wr.write("&id=" + tokens[0].substring(2).trim()); } wr.flush(); r.close(); InputStream in = conn.getInputStream(); IOUtils.copyTo(in, System.err); in.close(); wr.close(); } catch (IOException err) { err.printStackTrace(); } } }); }
Code Sample 2:
public File createReadmeFile(File dir, MavenProject mavenProject) throws IOException { InputStream is = getClass().getResourceAsStream("README.template"); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw); String content = sw.getBuffer().toString(); content = StringUtils.replace(content, "{project_name}", mavenProject.getArtifactId()); File readme = new File(dir, "README.TXT"); FileUtils.writeStringToFile(readme, content); return readme; }
|
11
|
Code Sample 1:
public void notifyIterationEnds(final IterationEndsEvent event) { log.info("moving files..."); File source = new File("deqsim.log"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log to its iteration directory."); } } int parallelCnt = 0; source = new File("deqsim.log." + parallelCnt); while (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log." + parallelCnt)); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log." + parallelCnt + " to its iteration directory."); } parallelCnt++; source = new File("deqsim.log." + parallelCnt); } source = new File("loads_out.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("loads_out.txt")); try { IOUtils.copyFile(source, destination); } catch (FileNotFoundException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } catch (IOException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } destination = new File("loads_in.txt"); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move loads_out.txt to loads_in.txt."); } } source = new File("linkprocs.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("linkprocs.txt")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move linkprocs.txt to its iteration directory."); } } }
Code Sample 2:
public static boolean copyFile(File sourceFile, File destFile) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(sourceFile).getChannel(); dstChannel = new FileOutputStream(destFile).getChannel(); long pos = 0; long count = srcChannel.size(); if (count > MAX_BLOCK_SIZE) { count = MAX_BLOCK_SIZE; } long transferred = Long.MAX_VALUE; while (transferred > 0) { transferred = dstChannel.transferFrom(srcChannel, pos, count); pos = transferred; } } catch (IOException e) { return false; } finally { if (srcChannel != null) { try { srcChannel.close(); } catch (IOException e) { } } if (dstChannel != null) { try { dstChannel.close(); } catch (IOException e) { } } } return true; }
|
00
|
Code Sample 1:
private String fetch(String urlstring) { String content = ""; try { URL url = new URL(urlstring); InputStream is = url.openStream(); BufferedReader d = new BufferedReader(new InputStreamReader(is)); String s; while (null != (s = d.readLine())) { content = content + s + "\n"; } is.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return content; }
Code Sample 2:
public ArrayList<Tweet> getTimeLine() { try { HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~/network/updates?scope=self"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); return null; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); SAXParserFactory spf = SAXParserFactory.newInstance(); StringReader XMLout = new StringReader(sBuf.toString()); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xmlParserLinkedin gwh = new xmlParserLinkedin(); xr.setContentHandler(gwh); xr.parse(new InputSource(XMLout)); return gwh.getParsedData(); } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (IOException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (ParserConfigurationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (SAXException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } return null; }
|
00
|
Code Sample 1:
public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new MyException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80), new UsernamePasswordCredentials("username", "password")); BasicHttpContext localcontext = new BasicHttpContext(); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", "some realm"); digestAuth.overrideParamter("nonce", "whatever"); localcontext.setAttribute("preemptive-auth", digestAuth); httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); httpclient.addResponseInterceptor(new PersistentDigest()); HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); entity.consumeContent(); } } }
|
00
|
Code Sample 1:
public static void parseSohuStock(ArrayList<String> dataSource, final ArrayList<SohuStockBean> sohuStockBeanList) throws IOReactorException, InterruptedException { HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.start(); if (dataSource != null && dataSource.size() > 0) { final CountDownLatch latch = new CountDownLatch(dataSource.size()); for (int i = 0; i < dataSource.size(); i++) { final HttpGet request = new HttpGet(dataSource.get(i)); httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine()); try { HttpEntity he = response.getEntity(); try { String resp = EntityUtils.toString(he, "gb2312"); if (resp != null && resp.length() > 0) { SohuStockBean shstBean = SohuStockPostProcess.postSohuStockBeanProcess(resp); sohuStockBeanList.add(shstBean); } count++; } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } latch.countDown(); } catch (RuntimeException re) { latch.countDown(); } } public void failed(final Exception ex) { latch.countDown(); } public void cancelled() { latch.countDown(); } }); } latch.await(); System.out.println("done"); } if (httpclient != null) { httpclient.shutdown(); } System.out.println(sohuStockBeanList.size()); }
Code Sample 2:
public static void copyFile(File source, File dest) throws Exception { log.warn("File names are " + source.toString() + " and " + dest.toString()); if (!dest.getParentFile().exists()) dest.getParentFile().mkdir(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
public void test() throws Exception { StorageString s = new StorageString("UTF-8"); s.addText("Test"); try { s.getOutputStream(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } try { s.getWriter(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } s.addText("ing is important"); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important", writer.toString()); }
Code Sample 2:
private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
|
00
|
Code Sample 1:
public static void initConfigurationV2(String cuttleConfiguration, javax.servlet.ServletContext context, List configFileList) throws Exception { ConfigureDigester.clearMap(); List rootList = new ArrayList(); InputStream is = null; if (cuttleConfiguration == null) { URL url = CompositePageUtil.class.getResource("/cuttle.xml"); if (url == null) url = CompositePageUtil.class.getClassLoader().getResource("/cuttle.xml"); is = url.openStream(); } else { is = context.getResourceAsStream(cuttleConfiguration); } parseConfigV2(rootList, is, context, configFileList); if (ConfigureDigester.getXmlCuttleConfiguration() != null && ConfigureDigester.getXmlCuttleConfiguration().getPlugins() != null) { for (int i = 0; i < ConfigureDigester.getXmlCuttleConfiguration().getPlugins().size(); i++) { XMLPlugin plugin = (XMLPlugin) ConfigureDigester.getXmlCuttleConfiguration().getPlugins().get(i); if (plugin.getConfigurePlugable() != null && !plugin.getConfigurePlugable().equals("")) { Class pluginable = Class.forName(plugin.getConfigurePlugable()); ConfigurePlugable pluginableObj = (ConfigurePlugable) pluginable.newInstance(); pluginableObj.initConfiguration(plugin.getConfigurationPath(), context); } } } }
Code Sample 2:
@Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); }
|
00
|
Code Sample 1:
public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("D:/work/test.txt"); FileOutputStream fout = new FileOutputStream("D:/work/output.txt"); FileChannel inChannel = fin.getChannel(); FileChannel outChannel = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int ret = inChannel.read(buffer); if (ret == -1) break; buffer.flip(); outChannel.write(buffer); buffer.clear(); } }
Code Sample 2:
public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); }
Code Sample 2:
public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
|
00
|
Code Sample 1:
public void run() { LogPrinter.log(Level.FINEST, "Started Download at : {0, date, long}", new Date()); if (!PipeConnected) { throw new IllegalStateException("You should connect the pipe before with getInputStream()"); } InputStream ins = null; if (IsAlreadyDownloaded) { LogPrinter.log(Level.FINEST, "The file already Exists open and foward the byte"); try { ContentLength = (int) TheAskedFile.length(); ContentType = URLConnection.getFileNameMap().getContentTypeFor(TheAskedFile.getName()); ins = new FileInputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { Pipe.write(buffer, 0, read); read = ins.read(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } } } else { LogPrinter.log(Level.FINEST, "the file does not exist locally so we try to download the thing"); File theDir = TheAskedFile.getParentFile(); if (!theDir.exists()) { theDir.mkdirs(); } for (URL url : ListFastest) { FileOutputStream fout = null; boolean OnError = false; long timestart = System.currentTimeMillis(); long bytecount = 0; try { URL newUrl = new URL(url.toString() + RequestedFile); LogPrinter.log(Level.FINEST, "the download URL = {0}", newUrl); URLConnection conn = newUrl.openConnection(); ContentType = conn.getContentType(); ContentLength = conn.getContentLength(); ins = conn.getInputStream(); fout = new FileOutputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { fout.write(buffer, 0, read); Pipe.write(buffer, 0, read); read = ins.read(buffer); bytecount += read; } Pipe.flush(); } catch (IOException e) { OnError = true; } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } if (fout != null) { try { fout.close(); } catch (IOException e) { } } } long timeend = System.currentTimeMillis(); if (OnError) { continue; } else { long timetook = timeend - timestart; BigDecimal speed = new BigDecimal(bytecount).multiply(new BigDecimal(1000)).divide(new BigDecimal(timetook), MathContext.DECIMAL32); for (ReportCalculatedStatistique report : Listener) { report.reportUrlStat(url, speed, timetook); } break; } } } LogPrinter.log(Level.FINEST, "download finished at {0,date,long}", new Date()); if (Pipe != null) { try { Pipe.close(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
private RssEvent getLastEvent() throws DocumentException, IOException { Document document = new SAXReader().read(url.openStream()); Element item = document.getRootElement().element("channel").element("item"); Date date = new Date(); String dateStr = item.element("pubDate").getStringValue(); try { date = dateFormat.parse(dateStr); } catch (ParseException e) { String message = MessageFormat.format("Unable to parse string \"{0}\" with pattern \"{1}\".", dateStr, FORMAT); logger.warn(message, e); } RssEvent event = new RssEvent(this, item.element("title").getStringValue(), item.element("link").getStringValue(), item.element("description").getStringValue(), item.element("author").getStringValue(), date); return event; }
|
11
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } }
Code Sample 2:
private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
|
00
|
Code Sample 1:
private String encryptPassword(String password) throws NoSuchAlgorithmException { MessageDigest encript = MessageDigest.getInstance("MD5"); encript.update(password.getBytes()); byte[] b = encript.digest(); int size = b.length; StringBuffer h = new StringBuffer(size); for (int i = 0; i < size; i++) { h.append(b[i]); } return h.toString(); }
Code Sample 2:
public static Document getDocument(URL url, boolean validate) throws QTIParseException { try { return getDocument(new InputSource(url.openStream()), validate, null); } catch (IOException ex) { throw new QTIParseException(ex); } }
|
11
|
Code Sample 1:
public static void copyFromHDFSMerge(String hdfsDir, String local) throws IOException { rmr(local); File f = new File(local); f.getAbsoluteFile().getParentFile().mkdirs(); HDFSDirInputStream inp = new HDFSDirInputStream(hdfsDir); FileOutputStream oup = new FileOutputStream(local); IOUtils.copyBytes(inp, oup, 65 * 1024 * 1024, true); }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
Code Sample 2:
private void criarQuestaoMultiplaEscolha(QuestaoMultiplaEscolha q) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO multipla_escolha (id_questao, texto, gabarito) VALUES (?,?,?)"; try { for (Alternativa alternativa : q.getAlternativa()) { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setString(2, alternativa.getTexto()); stmt.setBoolean(3, alternativa.getGabarito()); stmt.executeUpdate(); conexao.commit(); } } catch (SQLException e) { conexao.rollback(); throw e; } }
|
11
|
Code Sample 1:
private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
Code Sample 2:
public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
|
00
|
Code Sample 1:
private void loadProperties() throws IOException { if (properties == null) { return; } printDebugIfEnabled("Loading properties"); InputStream inputStream = configurationSource.openStream(); Properties newProperties = new Properties(); try { newProperties.load(inputStream); } finally { inputStream.close(); } String importList = newProperties.getProperty(KEY_IMPORT); if (importList != null) { importList = importList.trim(); if (importList.length() > 0) { String[] filesToImport = importList.split(","); if (filesToImport != null && filesToImport.length != 0) { String configurationContext = configurationSource.toExternalForm(); int lastSlash = configurationContext.lastIndexOf('/'); lastSlash += 1; configurationContext = configurationContext.substring(0, lastSlash); for (int i = 0; i < filesToImport.length; i++) { String filenameToImport = filesToImport[i]; URL urlToImport = new URL(configurationContext + filenameToImport); InputStream importStream = null; try { printDebugIfEnabled("Importing file", urlToImport); importStream = urlToImport.openStream(); newProperties.load(importStream); } catch (IOException e) { printError("Error importing properties file: " + filenameToImport + "(" + urlToImport + ")", e, true); } finally { if (importStream != null) importStream.close(); } } } } } if (devDebug) { Set properties = newProperties.entrySet(); printDebugIfEnabled("_____ Properties List START _____"); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); printDebugIfEnabled((String) entry.getKey(), entry.getValue()); } printDebugIfEnabled("______ Properties List END ______"); } properties.clear(); properties.putAll(newProperties); }
Code Sample 2:
public void loadXML(URL flux, int status, File file) { try { SAXBuilder sbx = new SAXBuilder(); try { if (file.exists()) { file.delete(); } if (!file.exists()) { URLConnection conn = flux.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(10000); InputStream is = conn.getInputStream(); OutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); out.close(); is.close(); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "Exeption retrieving XML", e); } try { document = sbx.build(new FileInputStream(file)); } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "xml error ", e); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "TsukiQueryError", e); } if (document != null) { root = document.getRootElement(); PopulateDatabase(root, status); } }
|
00
|
Code Sample 1:
protected static byte[] downloadAndSendBinary(String u, boolean saveOnDisk, File f) throws IOException { URL url = new URL(u); Authenticator.setDefault(new HTTPResourceAuthenticator()); HTTPResourceAuthenticator.addURL(url); logger.debug("Retrieving " + url.toString()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); URLConnection conn = url.openConnection(); conn.setRequestProperty("User-agent", "PS3 Media Server " + PMS.getVersion()); InputStream in = conn.getInputStream(); FileOutputStream fOUT = null; if (saveOnDisk && f != null) { fOUT = new FileOutputStream(f); } byte buf[] = new byte[4096]; int n = -1; while ((n = in.read(buf)) > -1) { bytes.write(buf, 0, n); if (fOUT != null) { fOUT.write(buf, 0, n); } } in.close(); if (fOUT != null) { fOUT.close(); } return bytes.toByteArray(); }
Code Sample 2:
public WordEntry[] getVariants(String word) throws MatchPackException { String upperWord = word.toUpperCase(); if (variantsDictionary == null) { try { long start = System.currentTimeMillis(); URL url = this.getClass().getResource("varlex.dic"); ObjectInputStream si = new ObjectInputStream(url.openStream()); variantsDictionary = (Map) si.readObject(); long end = System.currentTimeMillis(); System.out.println("loaded " + (end - start) + "ms"); si.close(); } catch (Exception e) { throw new MatchPackException("cannot load: varlex.dic " + e.getMessage()); } } List l = (List) variantsDictionary.get(upperWord); if (l == null) { return new WordEntry[0]; } return (WordEntry[]) l.toArray(new WordEntry[0]); }
|
00
|
Code Sample 1:
private Document post(String location, String content) throws ApplicationException { Document doc = null; try { URL url = new URL(location); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestMethod("POST"); uc.setRequestProperty("Content-Type", "application/xml"); uc.setRequestProperty("X-POST_DATA_FORMAT", "xml"); uc.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream()); out.write("<request>"); out.write("<token>" + configuration.getBackpackPassword() + "</token>"); if (content != null) { out.write("<item><content>" + content + "</content></item>"); } out.write("</request>"); out.close(); doc = XmlUtils.readDocumentFromInputStream(uc.getInputStream()); System.out.println(XmlUtils.toString(doc)); } catch (IOException e) { e.printStackTrace(); throw new ApplicationException(e); } return doc; }
Code Sample 2:
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
|
11
|
Code Sample 1:
@SuppressWarnings("finally") private void compress(File src) throws IOException { if (this.switches.contains(Switch.test)) return; checkSourceFile(src); if (src.getPath().endsWith(".bz2")) { this.log.println("WARNING: skipping file because it already has .bz2 suffix:").println(src); return; } final File dst = new File(src.getPath() + ".bz2").getAbsoluteFile(); if (!checkDestFile(dst)) return; FileChannel inChannel = null; FileChannel outChannel = null; FileOutputStream fileOut = null; BZip2OutputStream bzOut = null; FileLock inLock = null; FileLock outLock = null; try { inChannel = new FileInputStream(src).getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); fileOut = new FileOutputStream(dst); outChannel = fileOut.getChannel(); bzOut = new BZip2OutputStream( new BufferedXOutputStream(fileOut, 8192), Math.min( (this.blockSize == -1) ? BZip2OutputStream.MAX_BLOCK_SIZE : this.blockSize, BZip2OutputStream.chooseBlockSize(inSize) ) ); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); final boolean showProgress = this.switches.contains(Switch.showProgress); long pos = 0; int progress = 0; if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } while (true) { final long maxStep = showProgress ? Math.max(8192, (inSize - pos) / MAX_PROGRESS) : (inSize - pos); if (maxStep <= 0) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } else { final long step = inChannel.transferTo(pos, maxStep, bzOut); if ((step == 0) && (inChannel.size() != inSize)) throw error("file " + src + " has been modified concurrently by another process"); pos += step; if (showProgress) { final double p = (double) pos / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } inLock.release(); inChannel.close(); bzOut.closeInstance(); final long outSize = outChannel.position(); outChannel.truncate(outSize); outLock.release(); fileOut.close(); if (this.verbose) { final double ratio = (inSize == 0) ? (outSize * 100) : ((double) outSize / (double) inSize); this.log.print("raw size: ").print(inSize) .print("; compressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } } catch (final IOException ex) { IO.tryClose(inChannel); IO.tryClose(bzOut); IO.tryClose(fileOut); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } }
Code Sample 2:
public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
|
11
|
Code Sample 1:
public static String createRecoveryContent(String password) { try { password = encryptGeneral1(password); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recovery_file"); 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())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String textContent = root.getTextContent(); return textContent; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
Code Sample 2:
protected void handleUrl(URL url) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; boolean moreResults = false; while ((s = in.readLine()) != null) { if (s.indexOf("<h1>Search Results</h1>") > -1) { System.err.println("found severals result"); moreResults = true; } else if (s.indexOf("Download <a href=") > -1) { if (s.indexOf("in JCAMP-DX format.") > -1) { System.err.println("download masspec"); super.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } moreResults = false; } if (moreResults == true) { if (s.indexOf("<li><a href=\"/cgi/cbook.cgi?ID") > -1) { System.err.println("\tdownloading new url " + new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); this.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } } } }
|
00
|
Code Sample 1:
public void run() { long id = 0; try { URL url = new URL(httpRequest + blockSize); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); try { String str = in.readLine(); if (str == null) { throw new IllegalStateException("Parsing error"); } if (str.matches(".*SUCCESS.*")) { str = in.readLine(); if (str.matches(".*Start:.*")) { str = in.readLine(); id = Long.parseLong(str); } else { throw new IllegalStateException("Invalid response for blocksize(" + blockSize + "):" + str); } } else { throw new IllegalStateException("Invalid response for blocksize(" + blockSize + "):" + str); } } finally { in.close(); } if (id <= 0) throw new IllegalStateException("Invalid GUID start value " + id); synchronized (ids) { boolean absent = ids.add(new Long(id)); if (!absent) { logErrorMessage(id + " already exists for thread " + Thread.currentThread().getName()); } } } catch (Exception e) { logErrorMessage("Unexpected IdGenerator thread failure" + e.getMessage()); e.printStackTrace(); } finally { synchronized (test) { test.liveThreads--; test.notify(); } } }
Code Sample 2:
public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String isbn = null; HttpGet get = null; while ((isbn = br.readLine().split(" ")[0]) != null) { System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn)); get = new HttpGet(String.format(isbnSearchUrl, isbn)); HttpResponse resp = httpclient.execute(get); Scanner s = new Scanner(resp.getEntity().getContent()); String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0); if (pattern != null) { MatchResult match = s.match(); if (match.groupCount() == 3) { if (match.group(2) == null) { System.out.println(isbn + ": copies available"); } else { System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies"); } } } else { System.out.println(isbn + ": no match"); } get.abort(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { String urltext = "http://www.vogella.de"; URL url = new URL(urltext); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); }
Code Sample 2:
public void add(Site site) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sqlStr = "insert into t_ip_site (id,name,description,ascii_name,site_path,remark_number,increment_index,use_status,appserver_id) VALUES(?,?,?,?,?,?,?,?,?)"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, site.getSiteID()); preparedStatement.setString(2, site.getName()); preparedStatement.setString(3, site.getDescription()); preparedStatement.setString(4, site.getAsciiName()); preparedStatement.setString(5, site.getPath()); preparedStatement.setInt(6, site.getRemarkNumber()); preparedStatement.setString(7, site.getIncrementIndex().trim()); preparedStatement.setString(8, String.valueOf(site.getUseStatus())); preparedStatement.setString(9, String.valueOf(site.getAppserverID())); preparedStatement.executeUpdate(); String[] path = new String[1]; path[0] = site.getPath(); selfDefineAdd(path, site, connection, preparedStatement); connection.commit(); int resID = site.getSiteID() + Const.SITE_TYPE_RES; String resName = site.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); site.wirteFile(); } catch (SQLException ex) { connection.rollback(); log.error("����վ��ʧ��!", ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
|
11
|
Code Sample 1:
private boolean writeResource(PluginProxy eclipseInstallPlugin, ResourceProxy translation, LocaleProxy locale) throws Exception { String translationResourceName = determineTranslatedResourceName(translation, locale); String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(Messages.getString("Characters_period"), File.separator); if (translation.getRelativePath().contains(pluginNameInDirFormat)) { return writeResourceToBundleClasspath(translation, locale); } else if (translationResourceName.contains(File.separator)) { String resourcePath = translationResourceName.substring(0, translationResourceName.lastIndexOf(File.separatorChar)); File resourcePathDirectory = new File(directory.getPath() + File.separatorChar + resourcePath); resourcePathDirectory.mkdirs(); } File fragmentResource = new File(directory.getPath() + File.separatorChar + translationResourceName); File translatedResource = new File(translation.getFileResource().getAbsolutePath()); FileChannel inputChannel = new FileInputStream(translatedResource).getChannel(); FileChannel outputChannel = new FileOutputStream(fragmentResource).getChannel(); inputChannel.transferTo(0, inputChannel.size(), outputChannel); inputChannel.close(); outputChannel.close(); return true; }
Code Sample 2:
public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
|
00
|
Code Sample 1:
private static byte[] get256RandomBits() throws IOException { URL url = null; try { url = new URL(SRV_URL); } catch (MalformedURLException e) { e.printStackTrace(); } HttpsURLConnection hu = (HttpsURLConnection) url.openConnection(); hu.setConnectTimeout(2500); InputStream is = hu.getInputStream(); byte[] content = new byte[is.available()]; is.read(content); is.close(); hu.disconnect(); byte[] randomBits = new byte[32]; String line = new String(content); Matcher m = DETAIL.matcher(line); if (m.find()) { for (int i = 0; i < 32; i++) randomBits[i] = (byte) (Integer.parseInt(m.group(1).substring(i * 2, i * 2 + 2), 16) & 0xFF); } return randomBits; }
Code Sample 2:
private CExtractHelper getData(String p_url) { CExtractHelper l_extractHelper = new CExtractHelper(); URL l_url; HttpURLConnection l_connection; try { System.out.println("Getting [" + p_url + "]"); l_url = new URL(p_url); try { URLConnection l_uconn = l_url.openConnection(); l_connection = (HttpURLConnection) l_uconn; l_connection.setConnectTimeout(2000); l_connection.setReadTimeout(2000); l_connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); l_connection.connect(); int l_responseCode = l_connection.getResponseCode(); String response = l_connection.getResponseMessage(); System.out.println("HTTP/1.x " + l_responseCode + " " + response); for (int j = 1; ; j++) { String l_header = l_connection.getHeaderField(j); String l_key = l_connection.getHeaderFieldKey(j); if (l_header == null || l_key == null) { break; } } InputStream l_inputStream = new BufferedInputStream(l_connection.getInputStream()); CRemoteXML l_parser = new CRemoteXML(); try { Document l_document = l_parser.parse(l_inputStream); PrintWriter l_writerOut = new PrintWriter(new OutputStreamWriter(System.out, charsetName), true); OutputFormat l_format = OutputFormat.createPrettyPrint(); XMLWriter l_xmlWriter = new XMLWriter(l_writerOut, l_format); l_xmlWriter.write(l_document); l_xmlWriter.flush(); l_connection.disconnect(); l_extractHelper.m_document = l_document; return l_extractHelper; } catch (DocumentException e) { e.printStackTrace(); l_connection.disconnect(); System.out.println("XML parsing issue"); l_extractHelper.m_generalFailure = true; } } catch (SocketTimeoutException e) { l_extractHelper.m_timeoutFailure = true; System.out.println("Timed out"); } catch (IOException e) { e.printStackTrace(); l_extractHelper.m_generalFailure = true; } } catch (MalformedURLException e) { e.printStackTrace(); l_extractHelper.m_generalFailure = true; } return l_extractHelper; }
|
11
|
Code Sample 1:
public static boolean verifyPassword(String digest, String password) { String alg = null; int size = 0; 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; } try { MessageDigest sha = MessageDigest.getInstance(alg); if (sha == null) { return false; } byte[][] hs = split(Base64.decode(digest), size); byte[] hash = hs[0]; byte[] salt = hs[1]; sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); return MessageDigest.isEqual(hash, pwhash); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } }
Code Sample 2:
public final String hashPassword(final String password) { try { if (salt == null) { salt = new byte[16]; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(System.currentTimeMillis()); sr.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] hash = md.digest(); for (int i = 0; i < (1999); i++) { md.reset(); hash = md.digest(hash); } return byteToString(hash, 60); } catch (Exception exception) { log.error(exception); return null; } }
|
00
|
Code Sample 1:
public static byte[] readUrl(URL url) { BufferedInputStream in = null; try { class Part { byte[] partData; int len; } in = new BufferedInputStream(url.openStream()); LinkedList<Part> parts = new LinkedList<Part>(); int len = 1; while (len > 0) { byte[] data = new byte[1024]; len = in.read(data); if (len > 0) { Part part = new Part(); part.partData = data; part.len = len; parts.add(part); } } int length = 0; for (Part part : parts) length += part.len; byte[] result = new byte[length]; int pos = 0; for (Part part : parts) { System.arraycopy(part.partData, 0, result, pos, part.len); pos += part.len; } return result; } catch (IOException e) { return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
Code Sample 2:
public Node external_open_url(Node startAt) throws Exception { if (inUse) { throw new InterpreterException(StdErrors.extend(StdErrors.Already_used, "File already open")); } inUse = true; startAt.isGoodArgsLength(false, 2); ExtURL url = new ExtURL(startAt.getSubNode(1, Node.TYPE_STRING).getString()); String protocol = url.getProtocol(); String mode = null; Node props = null; Node datas = null; byte[] buffer = null; String old_c = null; String old_r = null; int max_i = startAt.size() - 1; if (startAt.elementAt(max_i).getSymbolicValue_undestructive().isVList()) { props = startAt.getSubNode(max_i--, Node.TYPE_LIST); } int i_ = 2; if (i_ <= max_i) { mode = startAt.getSubNode(i_++, Node.TYPE_STRING).getString().toUpperCase().trim(); if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) { if (!(mode.equals("GET") || mode.equals("POST") || mode.equals("PUT"))) { throw new InterpreterException(128010, "Unsupported request methode"); } } else if (protocol.equalsIgnoreCase("ftp") || protocol.equalsIgnoreCase("file")) { if (!(mode.equalsIgnoreCase("r") || mode.equalsIgnoreCase("w"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("jar") || protocol.equalsIgnoreCase("stdin")) { if (!(mode.equalsIgnoreCase("r"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("tcp") || protocol.equalsIgnoreCase("ssl+tcp")) { if (!(mode.equalsIgnoreCase("rw"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("stdout") || protocol.equalsIgnoreCase("stderr")) { if (!(mode.equalsIgnoreCase("w"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else { throw new InterpreterException(128011, "Unsupported protocol"); } } if (i_ <= max_i) { if (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https")) { throw new InterpreterException(128016, "Unsupported request datas"); } datas = startAt.getSubNode(i_++, Node.TYPE_STRING | Node.TYPE_OBJECT); if (datas.isVObject()) { Object obj = datas.getVObjectExternalInstance(); if (External_Buffer.class.isInstance(obj)) { Buffer bbuffer = ((External_Buffer) obj).getBuffer(); buffer = bbuffer.read_bytes(); } else { throw new InterpreterException(StdErrors.extend(StdErrors.Invalid_parameter, "Object (" + obj.getClass().getName() + ") required " + External_Buffer.class.getName())); } } else { buffer = datas.getString().getBytes(); } } if (datas != null && mode != null && mode.equals("GET")) { throw new InterpreterException(128012, "GET request with data body"); } if (props != null && (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https"))) { throw new InterpreterException(128013, "Cannot handle header properties in request"); } try { if (protocol.equalsIgnoreCase("file") && mode != null && mode.equalsIgnoreCase("w")) { File f = new File(url.toURI()); outputStream = new FileOutputStream(f); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("tcp")) { tcpHost = url.getHost(); tcpPort = url.getPort(); if (tcpPort < 0 || tcpPort > 65535) { throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort)); } socket = new Socket(tcpHost, tcpPort); if (readTimeOut > 0) { socket.setSoTimeout(readTimeOut); } inputStream = socket.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); outputStream = socket.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("ssl+tcp")) { tcpHost = url.getHost(); tcpPort = url.getPort(); if (tcpPort < 0 || tcpPort > 65535) { throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort)); } SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(tcpHost, tcpPort); if (readTimeOut > 0) { socket.setSoTimeout(readTimeOut); } inputStream = socket.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); outputStream = socket.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("stdout")) { setBufOut(System.out); } else if (protocol.equalsIgnoreCase("stderr")) { setBufOut(System.err); } else if (protocol.equalsIgnoreCase("stdin")) { setBufIn(System.in); } else { urlConnection = url.openConnection(); if (connectTimeOut > 0) { urlConnection.setConnectTimeout(connectTimeOut); } if (readTimeOut > 0) { urlConnection.setReadTimeout(readTimeOut); } urlConnection.setUseCaches(false); urlConnection.setDoInput(true); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) urlConnection; if (props != null) { for (int i = 0; i < props.size(); i++) { Node pnode = props.getSubNode(i, Node.TYPE_DICO); String header_s = Node.getPairKey(pnode); String value_s = Node.node2VString(Node.getPairValue(pnode)).getString(); Interpreter.Log(" HTTP-Header: " + header_s + " : " + value_s); httpCon.setRequestProperty(header_s, value_s); } } if (mode != null && (mode.equals("POST") || mode.equals("PUT"))) { if (mode.equals("PUT")) { Interpreter.Log(" HTTP PUT: " + url.toString()); } else { Interpreter.Log(" HTTP POST: " + url.toString()); } urlConnection.setDoOutput(true); httpCon.setRequestMethod(mode); outputStream = urlConnection.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); output.write(buffer); output.flush(); } inputStream = urlConnection.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); } else { if (mode == null || (mode != null && mode.equalsIgnoreCase("r"))) { Interpreter.Log(" " + protocol + " read : " + url.toString()); inputStream = urlConnection.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); } else { Interpreter.Log(" " + protocol + " write : " + url.toString()); outputStream = urlConnection.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } } } } catch (Exception e) { throw e; } bytePos = 0; putHook(); return null; }
|
00
|
Code Sample 1:
public void adicionaCliente(ClienteBean cliente) { PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into cliente(nome,cpf,telefone,cursoCargo,bloqueado,ativo,tipo) values(?,?,?,?,?,?,?)"; try { pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, cliente.getNome()); pstmt.setString(2, cliente.getCPF()); pstmt.setString(3, cliente.getTelefone()); pstmt.setString(4, cliente.getCursoCargo()); pstmt.setString(5, cliente.getBloqueado()); pstmt.setString(6, cliente.getAtivo()); pstmt.setString(7, cliente.getTipo()); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { cliente.setIdCliente(rs.getLong(1)); } connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao inserir cliente.", ex1); } throw new RuntimeException("Erro ao inserir cliente.", ex); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } }
Code Sample 2:
private static void userAuth(String challenge) throws IOException { try { MessageDigest md = MessageDigest.getInstance("BrokenMD4"); String passwd = null; if (System.getProperty("jarsync.password.gui") != null) { JPasswordField pass = new JPasswordField(); JPanel panel = new JPanel(new GridLayout(2, 1)); panel.add(new JLabel("Password:")); panel.add(pass); JOptionPane.showMessageDialog(null, panel, remoteUser + '@' + remoteHost + "'s Password", JOptionPane.QUESTION_MESSAGE); passwd = new String(pass.getPassword()); } else { System.out.print(remoteUser + '@' + remoteHost + "'s password: "); passwd = Util.readLine(System.in); System.out.println(); } md.update(new byte[4]); md.update(passwd.getBytes("US-ASCII")); md.update(challenge.getBytes("US-ASCII")); byte[] response = md.digest(); Util.writeASCII(out, remoteUser + " " + Util.base64(response) + '\n'); out.flush(); } catch (NoSuchAlgorithmException nsae) { throw new IOException("could not create message digest."); } }
|
00
|
Code Sample 1:
@Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } if (status < 200 || status >= 400) return false; String url = this.url + "?title=Special:UserLogin&action=submitlogin&type=login&returnto=Main_Page&wpDomain=" + domain + "&wpLoginattempt=Log%20in&wpName=" + username + "&wpPassword=" + password; return true; }
Code Sample 2:
public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; }
|
00
|
Code Sample 1:
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int i; String dicomURL = request.getParameter("datasetURL"); String contentType = request.getParameter("contentType"); String studyUID = request.getParameter("studyUID"); String seriesUID = request.getParameter("seriesUID"); String objectUID = request.getParameter("objectUID"); dicomURL += "&contentType=" + contentType + "&studyUID=" + studyUID + "&seriesUID=" + seriesUID + "&objectUID=" + objectUID + "&transferSyntax=1.2.840.10008.1.2.1"; dicomURL = dicomURL.replace("+", "%2B"); InputStream is = null; DataInputStream dis = null; try { URL url = new URL(dicomURL); is = url.openStream(); dis = new DataInputStream(is); for (i = 0; i < dicomData.length; i++) dicomData[i] = dis.readUnsignedByte(); String windowCenter = getElementValue("00281050"); String windowWidth = getElementValue("00281051"); request.getSession(true).setAttribute(WINDOW_CENTER_PARAM, windowCenter == null ? null : windowCenter.trim()); request.getSession(true).setAttribute(WINDOW_WIDTH_PARAM, windowWidth == null ? null : windowWidth.trim()); dis.skipBytes(50000000); is.close(); dis.close(); out.println("Success"); out.close(); } catch (Exception e) { log.error("Unable to read and send the DICOM dataset page", e); } }
Code Sample 2:
public String getScore(int id) { String title = null; try { URL url = new URL(BASE_URL + id + ".html"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { if (line.contains("<title>")) { title = line.substring(line.indexOf("<title>") + 7, line.indexOf("</title>")); title = title.substring(0, title.indexOf("|")).trim(); break; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } return title; }
|
00
|
Code Sample 1:
public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String basePath = setupBean.getWebAppRfsPath(); if (!basePath.endsWith(File.separator)) { basePath += File.separator; } File file1; Random rnd = new Random(); do { file1 = new File(basePath + "test" + rnd.nextInt(1000)); } while (file1.exists()); boolean success = false; try { file1.createNewFile(); FileWriter fw = new FileWriter(file1); fw.write("aA1"); fw.close(); success = true; FileReader fr = new FileReader(file1); success = success && (fr.read() == 'a'); success = success && (fr.read() == 'A'); success = success && (fr.read() == '1'); success = success && (fr.read() == -1); fr.close(); success = file1.delete(); success = !file1.exists(); } catch (Exception e) { success = false; } if (!success) { testResult.setRed(); testResult.setInfo("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges."); testResult.setHelp("Not enough permissions to create/read/write a file"); testResult.setResult(RESULT_FAILED); } else { testResult.setGreen(); testResult.setResult(RESULT_PASSED); } return testResult; }
Code Sample 2:
public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; }
|
11
|
Code Sample 1:
private EventSeries<PhotoEvent> loadIncomingEvents(long reportID) { EventSeries<PhotoEvent> events = new EventSeries<PhotoEvent>(); try { URL url = new URL(SERVER_URL + XML_PATH + "reports.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = reader.readLine()) != null) { String[] values = str.split(","); if (values.length == 2) { long id = Long.parseLong(values[0]); if (id == reportID) { long time = Long.parseLong(values[1]); events.addEvent(new PhotoEvent(time)); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return events; }
Code Sample 2:
public static String doPostWithBasicAuthentication(URL url, String username, String password, String parameters, Map<String, String> headers) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(2000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (parameters != null) con.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.