label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static ParsedXML parseXML(URL url) throws ParseException { try { InputStream is = url.openStream(); ParsedXML px = parseXML(is); is.close(); return px; } catch (IOException e) { throw new ParseException("could not read from URL" + url.toString()); } } Code Sample 2: private ArrayList<XSPFTrackInfo> getPlaylist() { try { Log.d(TAG, "Getting playlist started"); String urlString = "http://" + mBaseURL + "/xspf.php?sk=" + mSession + "&discovery=0&desktop=1.4.1.57486"; if (mAlternateConn) { urlString += "&api_key=9d1bbaef3b443eb97973d44181d04e4b"; Log.d(TAG, "Using alternate connection method"); } URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFac.newDocumentBuilder(); Document doc = db.parse(is); Element root = doc.getDocumentElement(); NodeList titleNs = root.getElementsByTagName("title"); String stationName = "<unknown station>"; if (titleNs.getLength() > 0) { Element titleElement = (Element) titleNs.item(0); String res = ""; for (int i = 0; i < titleElement.getChildNodes().getLength(); i++) { Node item = titleElement.getChildNodes().item(i); if (item.getNodeType() == Node.TEXT_NODE) res += item.getNodeValue(); } stationName = URLDecoder.decode(res, "UTF-8"); } NodeList tracks = doc.getElementsByTagName("track"); ArrayList<XSPFTrackInfo> result = new ArrayList<XSPFTrackInfo>(); for (int i = 0; i < tracks.getLength(); i++) try { result.add(new XSPFTrackInfo(stationName, (Element) tracks.item(i))); } catch (Utils.ParseException e) { Log.e(TAG, "in getPlaylist", e); return null; } Log.d(TAG, "Getting playlist successful"); return result; } catch (Exception e) { Log.e(TAG, "in getPlaylist", e); return null; } }
11
Code Sample 1: public static String URLtoString(URL url) throws IOException { String xml = null; if (url != null) { URLConnection con = url.openConnection(); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); InputStream is = con.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] bytes = new byte[512]; for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) { buffer.write(bytes, 0, i); } xml = new String(buffer.toByteArray()); is.close(); buffer.close(); } return xml; } Code Sample 2: public static void upper() throws Exception { File input = new File("dateiname"); PostMethod post = new PostMethod("url"); post.setRequestBody(new FileInputStream(input)); if (input.length() < Integer.MAX_VALUE) post.setRequestContentLength((int) input.length()); else post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859�1"); HttpClient httpclient = new HttpClient(); httpclient.executeMethod(post); post.releaseConnection(); URL url = new URL("https://www.amazon.de/"); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); }
00
Code Sample 1: public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: private boolean get(String surl, File dst, Get get) throws IOException { boolean ret = false; InputStream is = null; OutputStream os = null; try { try { if (surl.startsWith("file://")) { is = new FileInputStream(surl.substring(7)); } else { URL url = new URL(surl); is = url.openStream(); } if (is != null) { os = new FileOutputStream(dst); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } } catch (ConnectException ex) { log("Connect exception " + ex.getMessage(), ex, 3); if (dst.exists()) dst.delete(); } catch (UnknownHostException ex) { log("Unknown host " + ex.getMessage(), ex, 3); } catch (FileNotFoundException ex) { log("File not found: " + ex.getMessage(), 3); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } if (ret) { try { is = new FileInputStream(dst); os = new FileOutputStream(getCachedFile(get)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; }
00
Code Sample 1: public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
00
Code Sample 1: public String getDigest(String s) throws Exception { MessageDigest md = MessageDigest.getInstance(hashName); md.update(s.getBytes()); byte[] dig = md.digest(); return Base16.toHexString(dig); } Code Sample 2: public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { 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) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: public static boolean insereCapitulo(final Connection con, Capitulo cap, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodCapitulo(con, cap); String text = desc.getTexto().replaceAll("[']", "\""); String titulo = cap.getTitulo().replaceAll("['\"]", ""); String coment = cap.getComentario().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + text + "')"); smt.executeUpdate("INSERT INTO capitulo VALUES(" + cap.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO cap_aut VALUES(" + cap.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "CAPITULO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } } Code Sample 2: @Override public String encryptPassword(String password) throws JetspeedSecurityException { if (securePasswords == false) { return password; } if (password == null) { return null; } try { if ("SHA-512".equals(passwordsAlgorithm)) { password = password + JetspeedResources.getString("aipo.encrypt_key"); MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); md.reset(); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < hash.length; i++) { sb.append(Integer.toHexString((hash[i] >> 4) & 0x0F)); sb.append(Integer.toHexString(hash[i] & 0x0F)); } return sb.toString(); } else { MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); byte[] digest = md.digest(password.getBytes(ALEipConstants.DEF_CONTENT_ENCODING)); ByteArrayOutputStream bas = new ByteArrayOutputStream(digest.length + digest.length / 3 + 1); OutputStream encodedStream = MimeUtility.encode(bas, "base64"); encodedStream.write(digest); encodedStream.flush(); encodedStream.close(); return bas.toString(); } } catch (Exception e) { logger.error("Unable to encrypt password." + e.getMessage(), e); return null; } }
11
Code Sample 1: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; } Code Sample 2: public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } }
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: private void alterarArtista(Artista artista) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE artista SET nome = ?,sexo = ?,email = ?,obs = ?,telefone = ? where numeroinscricao = ?"; ps = conn.prepareStatement(sql); ps.setString(1, artista.getNome()); ps.setBoolean(2, artista.isSexo()); ps.setString(3, artista.getEmail()); ps.setString(4, artista.getObs()); ps.setString(5, artista.getTelefone()); ps.setInt(6, artista.getNumeroInscricao()); ps.executeUpdate(); alterarEndereco(conn, ps, artista); delObras(conn, ps, artista.getNumeroInscricao()); sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); for (Obra obra : artista.getListaObras()) { salvarObra(conn, ps, obra, artista.getNumeroInscricao()); } conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength - 1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; }
11
Code Sample 1: public void saveSharedFiles(List<FrostSharedFileItem> sfFiles) throws SQLException { Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); Statement s = conn.createStatement(); s.executeUpdate("DELETE FROM SHAREDFILES"); s.close(); s = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO SHAREDFILES (" + "path,size,fnkey,sha,owner,comment,rating,keywords," + "lastuploaded,uploadcount,reflastsent,requestlastreceived,requestsreceivedcount,lastmodified) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (Iterator<FrostSharedFileItem> i = sfFiles.iterator(); i.hasNext(); ) { FrostSharedFileItem sfItem = i.next(); int ix = 1; ps.setString(ix++, sfItem.getFile().getPath()); ps.setLong(ix++, sfItem.getFileSize()); ps.setString(ix++, sfItem.getChkKey()); ps.setString(ix++, sfItem.getSha()); ps.setString(ix++, sfItem.getOwner()); ps.setString(ix++, sfItem.getComment()); ps.setInt(ix++, sfItem.getRating()); ps.setString(ix++, sfItem.getKeywords()); ps.setLong(ix++, sfItem.getLastUploaded()); ps.setInt(ix++, sfItem.getUploadCount()); ps.setLong(ix++, sfItem.getRefLastSent()); ps.setLong(ix++, sfItem.getRequestLastReceived()); ps.setInt(ix++, sfItem.getRequestsReceived()); ps.setLong(ix++, sfItem.getLastModified()); ps.executeUpdate(); } ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (Throwable t) { logger.log(Level.SEVERE, "Exception during save", t); try { conn.rollback(); } catch (Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); } try { conn.setAutoCommit(true); } catch (Throwable t1) { } } finally { AppLayerDatabase.getInstance().givePooledConnection(conn); } } Code Sample 2: public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,pilot_id_seq.nextval)"); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); if (pilotData.id != 0) { psta.setInt(19, pilotData.id); } psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } }
00
Code Sample 1: public static IBiopaxModel read(URL url) throws ReactionException, IOException { IBiopaxModel model = null; InputStream in = null; try { in = url.openStream(); model = read(in); } catch (IOException e) { LOGGER.error("Unable to read from URL " + url, e); } finally { if (in != null) in.close(); } return model; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: private void initURL() { try { log.fine("Checking: " + locator); URLConnection conn = URIFactory.url(locator).openConnection(); conn.setUseCaches(false); log.info(conn.getHeaderFields().toString()); String header = conn.getHeaderField(null); if (header.contains("404")) { log.info("404 file not found: " + locator); return; } if (header.contains("500")) { log.info("500 server error: " + locator); return; } if (conn.getContentLength() > 0) { byte[] buffer = new byte[50]; conn.getInputStream().read(buffer); if (new String(buffer).trim().startsWith("<!DOCTYPE")) return; } else if (conn.getContentLength() == 0) { exists = true; return; } exists = true; length = conn.getContentLength(); } catch (Exception ioe) { System.err.println(ioe); } }
00
Code Sample 1: public void testAutoCommit() throws Exception { Connection con = getConnectionOverrideProperties(new Properties()); try { Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate("create table #testAutoCommit (i int)")); con.setAutoCommit(false); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (0)")); con.setAutoCommit(false); con.rollback(); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (1)")); con.setAutoCommit(true); con.setAutoCommit(false); con.rollback(); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("select i from #testAutoCommit"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } finally { con.close(); } } Code Sample 2: @Override public void run() { while (run) { try { URL url = new URL("http://" + server.getIp() + "/" + tomcat.getName() + "/ui/pva/version.jsp?RT=" + System.currentTimeMillis()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("UTF-8"))); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("currentversion")) { String s = inputLine.substring(inputLine.indexOf("=") + 1, inputLine.length()); tomcat.setDetailInfo(s.trim()); } } in.close(); tomcat.setIsAlive(true); } catch (Exception e) { tomcat.setIsAlive(false); } try { Thread.sleep(60000); } catch (InterruptedException e) { } } }
11
Code Sample 1: char[] DigestCalcHA1(String algorithm, String userName, String realm, String password, String nonce, String clientNonce) throws SaslException { byte[] hash; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(realm.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); hash = md.digest(); if ("md5-sess".equals(algorithm)) { md.update(hash); md.update(":".getBytes("UTF-8")); md.update(nonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(clientNonce.getBytes("UTF-8")); hash = md.digest(); } } catch (NoSuchAlgorithmException e) { throw new SaslException("No provider found for MD5 hash", e); } catch (UnsupportedEncodingException e) { throw new SaslException("UTF-8 encoding not supported by platform.", e); } return convertToHex(hash); } Code Sample 2: private String generateUniqueIdMD5(String workgroupIdString, String runIdString) { String passwordUnhashed = workgroupIdString + "-" + runIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(passwordUnhashed.getBytes(), 0, passwordUnhashed.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; }
11
Code Sample 1: @Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); if (remainingsize >= splitsize) { in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; } else { in.transferTo(pos, remainingsize, out); } pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
11
Code Sample 1: public static byte[] clearPassToUserPassword(String clearpass, HashAlg alg, byte[] salt) { if (alg == null) { throw new IllegalArgumentException("Invalid hash argorithm."); } try { MessageDigest digester = null; StringBuilder resultInText = new StringBuilder(); switch(alg) { case MD5: resultInText.append("{MD5}"); digester = MessageDigest.getInstance("MD5"); break; case SMD5: resultInText.append("{SMD5}"); digester = MessageDigest.getInstance("MD5"); break; case SHA: resultInText.append("{SHA}"); digester = MessageDigest.getInstance("SHA"); break; case SSHA: resultInText.append("{SSHA}"); digester = MessageDigest.getInstance("SHA"); break; default: break; } digester.reset(); digester.update(clearpass.getBytes(DEFAULT_ENCODING)); byte[] hash = null; if (salt != null && (alg == HashAlg.SMD5 || alg == HashAlg.SSHA)) { digester.update(salt); hash = ArrayUtils.addAll(digester.digest(), salt); } else { hash = digester.digest(); } resultInText.append(new String(Base64.encodeBase64(hash), DEFAULT_ENCODING)); return resultInText.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException uee) { log.warn("Error occurred while hashing password ", uee); return new byte[0]; } catch (java.security.NoSuchAlgorithmException nse) { log.warn("Error occurred while hashing password ", nse); return new byte[0]; } } Code Sample 2: public String encryptStringWithKey(String to_be_encrypted, String aKey) { String encrypted_value = ""; char xdigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException exc) { globalErrorDictionary.takeValueForKey(("Security package does not contain appropriate algorithm"), ("Security package does not contain appropriate algorithm")); log.error("Security package does not contain appropriate algorithm"); return encrypted_value; } if (to_be_encrypted != null) { byte digest[]; byte fudge_constant[]; try { fudge_constant = ("X#@!").getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudge_constant = ("X#@!").getBytes(); } byte fudgetoo_part[] = { (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)] }; int i = 0; if (aKey != null) { try { fudgetoo_part = aKey.getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudgetoo_part = aKey.getBytes(); } } messageDigest.update(fudge_constant); try { messageDigest.update(to_be_encrypted.getBytes("UTF8")); } catch (UnsupportedEncodingException uee) { messageDigest.update(to_be_encrypted.getBytes()); } messageDigest.update(fudgetoo_part); digest = messageDigest.digest(); encrypted_value = new String(fudgetoo_part); for (i = 0; i < digest.length; i++) { int mashed; char temp[] = new char[2]; if (digest[i] < 0) { mashed = 127 + (-1 * digest[i]); } else { mashed = digest[i]; } temp[0] = xdigit[mashed / 16]; temp[1] = xdigit[mashed % 16]; encrypted_value = encrypted_value + (new String(temp)); } } return encrypted_value; }
11
Code Sample 1: public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); } Code Sample 2: public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = 67076096; long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: private void delay(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String url = request.getRequestURL().toString(); if (delayed.contains(url)) { delayed.remove(url); LOGGER.info(MessageFormat.format("Loading delayed resource at url = [{0}]", url)); chain.doFilter(request, response); } else { LOGGER.info("Returning resource = [LoaderApplication.swf]"); InputStream input = null; OutputStream output = null; try { input = getClass().getResourceAsStream("LoaderApplication.swf"); output = response.getOutputStream(); delayed.add(url); response.setHeader("Cache-Control", "no-cache"); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } }
11
Code Sample 1: private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; } Code Sample 2: public void exportFile() { String expfolder = PropertyHandler.getInstance().getProperty(PropertyHandler.KINDLE_EXPORT_FOLDER_KEY); File out = new File(expfolder + File.separator + previewInfo.getTitle() + ".prc"); File f = new File(absPath); try { FileOutputStream fout = new FileOutputStream(out); FileInputStream fin = new FileInputStream(f); int read = 0; byte[] buffer = new byte[1024 * 1024]; while ((read = fin.read(buffer)) > 0) { fout.write(buffer, 0, read); } fin.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void addFinance(int clubid, int quarterid, String date, String desc, String loc, BigDecimal amount) throws FinanceException, SQLException { String budgetQuery = "SELECT used, available FROM Budget WHERE club_id=" + clubid + " and quarter_id=" + quarterid + ";"; String financeUpdate = "INSERT INTO Finance (`club_id`, `transaction_date`, `description`, `location`, `amount`) VALUES ('" + clubid + "', '" + date + "', '" + desc + "', '" + "', '" + loc + "', '" + amount + "');"; Budget b = new Budget(); try { cn.setAutoCommit(false); Statement sm = cn.createStatement(); ResultSet rs = sm.executeQuery(budgetQuery); if (rs.first()) { b.used = rs.getBigDecimal(1); b.available = rs.getBigDecimal(2); } else { throw new FinanceException("No budget exists for this club!!"); } if (b.available.compareTo(amount.negate()) >= 0) { if (amount.equals(new BigDecimal(0))) ; { b.used = b.used.subtract(amount); } b.available = b.available.add(amount); sm = cn.createStatement(); sm.executeUpdate(financeUpdate); sm = cn.createStatement(); sm.executeUpdate("Update Budget SET used = " + b.used + ", amount = " + b.available + " WHERE club_id=" + clubid + " and quarter_id=" + quarterid + ";"); cn.commit(); } else { throw new FinanceException("The proposed expenditure is not within the club's budget."); } } catch (SQLException e) { cn.rollback(); throw e; } finally { cn.setAutoCommit(true); } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException, IllegalArgumentException { if (src.isDirectory()) throw new IllegalArgumentException("Source file is a directory"); if (dest.isDirectory()) throw new IllegalArgumentException("Destination file is a directory"); int bufferSize = 4 * 1024; InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
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 copy(File inputFile, File target) throws IOException { if (!inputFile.exists()) return; OutputStream output = new FileOutputStream(target); InputStream input = new BufferedInputStream(new FileInputStream(inputFile)); int b; while ((b = input.read()) != -1) output.write(b); output.close(); input.close(); }
00
Code Sample 1: public boolean optimize(int coreId) { try { URL url = new URL(solrUrl + "/core" + coreId + "/update"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Content-type", "text/xml"); conn.setRequestProperty("charset", "utf-8"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); System.out.println("******************optimizing"); wr.write("<optimize/>"); 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(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } Code Sample 2: public static void main(String[] args) throws Exception { String localSrc = args[0]; String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(dst), conf); OutputStream out = fs.create(new Path(dst), new Progressable() { public void progress() { System.out.print("."); } }); IOUtils.copyBytes(in, out, 4096, true); }
00
Code Sample 1: @Override public void updateItems(List<InputQueueItem> toUpdate) throws DatabaseException { if (toUpdate == null) throw new NullPointerException("toUpdate"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } try { PreparedStatement deleteSt = getConnection().prepareStatement(DELETE_ALL_ITEMS_STATEMENT); PreparedStatement selectCount = getConnection().prepareStatement(SELECT_NUMBER_ITEMS_STATEMENT); ResultSet rs = selectCount.executeQuery(); rs.next(); int totalBefore = rs.getInt(1); int deleted = deleteSt.executeUpdate(); int updated = 0; for (InputQueueItem item : toUpdate) { updated += getItemInsertStatement(item).executeUpdate(); } if (totalBefore == deleted && updated == toUpdate.size()) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + selectCount + "\" and \"" + deleteSt + "\"."); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + selectCount + "\" and \"" + deleteSt + "\"."); } } catch (SQLException e) { LOGGER.error(e); } finally { closeConnection(); } } Code Sample 2: InputStream openReader(String s) { System.err.println("Fetcher: trying url " + s); try { URL url = new URL(s); HttpURLConnection con = (HttpURLConnection) url.openConnection(); return url.openStream(); } catch (IOException e) { } return null; }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static final byte[] getHttpStream(final String uri) { URL url; try { url = new URL(uri); } catch (Exception e) { return null; } InputStream is = null; try { is = url.openStream(); } catch (Exception e) { return null; } ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] arrayByte = null; try { arrayByte = new byte[4096]; int read; while ((read = is.read(arrayByte)) >= 0) { os.write(arrayByte, 0, read); } arrayByte = os.toByteArray(); } catch (IOException e) { return null; } finally { try { if (os != null) { os.close(); os = null; } if (is != null) { is.close(); is = null; } } catch (IOException e) { } } return arrayByte; } Code Sample 2: public void Sort(int a[]) { for (int i = a.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } }
00
Code Sample 1: public static String generateToken(ClientInfo clientInfo) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); Random rand = new Random(); String random = clientInfo.getIpAddress() + ":" + clientInfo.getPort() + ":" + rand.nextInt(); md5.update(random.getBytes()); String token = toHexString(md5.digest((new Date()).toString().getBytes())); clientInfo.setToken(token); return token; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: protected void initializeFromURL(URL url, AVList params) throws IOException { URLConnection connection = url.openConnection(); String message = this.validateURLConnection(connection, SHAPE_CONTENT_TYPES); if (message != null) { throw new IOException(message); } this.shpChannel = Channels.newChannel(WWIO.getBufferedInputStream(connection.getInputStream())); URLConnection shxConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), INDEX_FILE_SUFFIX)); if (shxConnection != null) { message = this.validateURLConnection(shxConnection, INDEX_CONTENT_TYPES); if (message != null) Logging.logger().warning(message); else { InputStream shxStream = this.getURLStream(shxConnection); if (shxStream != null) this.shxChannel = Channels.newChannel(WWIO.getBufferedInputStream(shxStream)); } } URLConnection prjConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), PROJECTION_FILE_SUFFIX)); if (prjConnection != null) { message = this.validateURLConnection(prjConnection, PROJECTION_CONTENT_TYPES); if (message != null) Logging.logger().warning(message); else { InputStream prjStream = this.getURLStream(prjConnection); if (prjStream != null) this.prjChannel = Channels.newChannel(WWIO.getBufferedInputStream(prjStream)); } } this.setValue(AVKey.DISPLAY_NAME, url.toString()); this.initialize(params); URL dbfURL = WWIO.makeURL(WWIO.replaceSuffix(url.toString(), ATTRIBUTE_FILE_SUFFIX)); if (dbfURL != null) { try { this.attributeFile = new DBaseFile(dbfURL); } catch (Exception e) { } } }
00
Code Sample 1: protected URLConnection openConnection(URL url) throws IOException { URLConnection con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(ks, password, alias)); scon.setHostnameVerifier(SSLUtil.getHostnameVerifier(SSLUtil.HOSTCERT_MIN_CHECK)); } catch (GeneralException e) { throw new IOException(e.getMessage()); } catch (GeneralSecurityException e) { throw new IOException(e.getMessage()); } } return con; } Code Sample 2: public String getHTTPContent(String sUrl, String encode, String cookie, String host, String referer) { HttpURLConnection connection = null; InputStream in = null; StringBuffer strResult = new StringBuffer(); try { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); if (!isStringNull(host)) this.setHttpInfo(connection, cookie, host, referer); connection.connect(); int httpStatus = connection.getResponseCode(); if (httpStatus != 200) log.info("getHTTPConent error httpStatus - " + httpStatus); in = new BufferedInputStream(connection.getInputStream()); String inputLine = null; byte[] b = new byte[40960]; int len = 0; while ((len = in.read(b)) > 0) { inputLine = new String(b, 0, len, encode); strResult.append(inputLine.replaceAll("[\t\n\r ]", " ")); } in.close(); } catch (IOException e) { log.warn("SpiderUtil getHTTPConent IOException -> ", e); } finally { if (in != null) try { in.close(); } catch (IOException e) { } } return strResult.toString(); }
00
Code Sample 1: public static synchronized String getMD5_Base64(final String input) { if (isInited == false) { isInited = true; try { digest = MessageDigest.getInstance("MD5"); } catch (Exception ex) { logger.error("Cannot get MessageDigest. Application may fail to run correctly.", ex); } } if (digest == null) { return input; } try { digest.update(input.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException ex) { logger.error("Assertion: This should never occur."); } byte[] rawData = digest.digest(); byte[] encoded = Base64.encode(rawData); String retValue = new String(encoded); return retValue; } Code Sample 2: public static void find(String pckgname, Class tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = RTSI.class.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } }
00
Code Sample 1: public String readURL(URL url) throws JasenException { OutputStream out = new ByteArrayOutputStream(); InputStream in = null; String html = null; NonBlockingStreamReader reader = null; try { in = url.openStream(); reader = new NonBlockingStreamReader(); reader.read(in, out, readBufferSize, readTimeout, null); html = new String(((ByteArrayOutputStream) out).toByteArray()); } catch (IOException e) { throw new JasenException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return html; } Code Sample 2: private void copyValidFile(File file, int cviceni) { try { String filename = String.format("%s%s%02d%s%s", validovane, File.separator, cviceni, File.separator, file.getName()); boolean copy = false; File newFile = new File(filename); if (newFile.exists()) { if (file.lastModified() > newFile.lastModified()) copy = true; else copy = false; } else { newFile.createNewFile(); copy = true; } if (copy) { String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(newFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); newFile.setLastModified(file.lastModified()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copy(File src, File dest) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); }
11
Code Sample 1: public void zipDocsetFiles(SaxHandler theXmlHandler, int theEventId, Attributes theAtts) throws BpsProcessException { ZipOutputStream myZipOut = null; BufferedInputStream myDocumentInputStream = null; String myFinalFile = null; String myTargetPath = null; String myTargetFileName = null; String myInputFileName = null; byte[] myBytesBuffer = null; int myLength = 0; try { myZipOut = new ZipOutputStream(new FileOutputStream(myFinalFile)); myZipOut.putNextEntry(new ZipEntry(myTargetPath + myTargetFileName)); myDocumentInputStream = new BufferedInputStream(new FileInputStream(myInputFileName)); while ((myLength = myDocumentInputStream.read(myBytesBuffer, 0, 4096)) != -1) myZipOut.write(myBytesBuffer, 0, myLength); myZipOut.closeEntry(); myZipOut.close(); } catch (FileNotFoundException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "FileNotFoundException while building zip dest file")); } catch (IOException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "IOException while building zip dest file")); } } Code Sample 2: protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Session session = HibernateUtil.getInstance().getSession(); response.setBufferSize(65536); ServletOutputStream outStream = response.getOutputStream(); File file = null; FileData fileData = null; try { String fileParameter = request.getParameter("file"); String disposition = request.getParameter("disposition"); if (fileParameter == null || fileParameter.equals("")) { String pi = request.getPathInfo(); int lastSlashIndex = pi.lastIndexOf("/") + 1; fileParameter = pi.substring(lastSlashIndex, pi.indexOf("_", pi.lastIndexOf("/"))); } if (fileParameter == null || fileParameter.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.flushBuffer(); Logger.log("file parameter not specified"); return; } if (disposition == null || disposition.equals("")) { String pi = request.getPathInfo(); String filename = pi.substring(pi.lastIndexOf("/") + 1); int underscoreIndex = filename.indexOf("_") + 1; disposition = filename.substring(underscoreIndex, filename.indexOf("_", underscoreIndex)); } file = (File) session.load(File.class, new Long(fileParameter)); Logger.log("Content requested=" + file.getName() + ":" + fileParameter + " Referral: " + request.getParameter("referer")); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long fileDate = file.getLastModifiedDate() - (file.getLastModifiedDate() % 1000); if (fileDate <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } response.setContentType(file.getContentType()); response.setHeader("Content-Description", file.getName()); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); response.flushBuffer(); Logger.log("Conditional GET: " + file.getName()); return; } User authUser = baseService.getAuthenticatedUser(session, request, response); if (!SecurityHelper.doesUserHavePermission(session, authUser, file, Permission.PERM.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); Logger.log("Forbidden content requested: " + fileParameter); return; } String contentType = file.getContentType(); response.setContentType(contentType); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } String name = file.getName(); response.setHeader("Content-Description", name); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); java.io.File possibleDataFile = new java.io.File(BaseSystem.getTempDir() + file.getNameOnDisk()); if (possibleDataFile.exists()) { Logger.log("File exists in " + BaseSystem.getTempDir() + " pulling " + possibleDataFile.getName()); FileInputStream fileInputStream = new FileInputStream(possibleDataFile); try { IOUtils.copy(fileInputStream, outStream); } finally { try { fileInputStream.close(); } catch (Throwable t) { } } } else { List<FileData> fileDataList = HibernateUtil.getInstance().executeQuery(session, "from " + FileData.class.getSimpleName() + " where permissibleObject.id = " + file.getId()); if (fileDataList.size() == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); Logger.log("Requested content not found: " + fileParameter); response.flushBuffer(); return; } fileData = (FileData) fileDataList.get(0); FileOutputStream fileOutputStream = null; try { java.io.File tmpDir = new java.io.File(BaseSystem.getTempDir()); tmpDir.mkdirs(); fileOutputStream = new FileOutputStream(possibleDataFile); IOUtils.write(fileData.getData(), fileOutputStream); } catch (Throwable t) { Logger.log(t); } finally { try { fileOutputStream.close(); } catch (Throwable t) { } } IOUtils.write(fileData.getData(), outStream); } } catch (Throwable t) { Logger.log(t); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.flushBuffer(); } catch (Throwable tt) { } try { response.reset(); response.resetBuffer(); } catch (Throwable tt) { } } finally { file = null; fileData = null; try { outStream.flush(); } catch (Throwable t) { } try { outStream.close(); } catch (Throwable t) { } try { session.close(); } catch (Throwable t) { } } }
00
Code Sample 1: private static HttpURLConnection _getConnection(HttpPrincipal httpPrincipal) throws IOException { if (httpPrincipal == null || httpPrincipal.getUrl() == null) { return null; } URL url = null; if ((httpPrincipal.getUserId() <= 0) || (httpPrincipal.getPassword() == null)) { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/liferay/do"); } else { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/secure/liferay/do"); } HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setDoInput(true); urlc.setDoOutput(true); urlc.setUseCaches(false); urlc.setRequestMethod("POST"); if ((httpPrincipal.getUserId() > 0) && (httpPrincipal.getPassword() != null)) { String userNameAndPassword = httpPrincipal.getUserId() + ":" + httpPrincipal.getPassword(); urlc.setRequestProperty("Authorization", "Basic " + Base64.encode(userNameAndPassword.getBytes())); } return urlc; } Code Sample 2: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); }
00
Code Sample 1: public static String encryption(String oldPass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(oldPass.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } String pass32 = buf.toString(); return pass32; } Code Sample 2: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); String year = req.getParameter("year").toString(); String round = req.getParameter("round").toString(); resp.getWriter().println("<html><body>"); resp.getWriter().println("Searching for : " + year + ", " + round + "<br/>"); StringBuffer sb = new StringBuffer("http://www.dfb.de/bliga/bundes/archiv/"); sb.append(year).append("/xml/blm_e_").append(round).append("_").append(year.substring(2, 4)).append(".xml"); resp.getWriter().println(sb.toString() + "<br/><br/>"); try { URL url = new URL(sb.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer xml = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { xml.append(line); } Document document = DocumentHelper.parseText(xml.toString()); List termine = document.selectNodes("//ergx/termin"); int index = 1; for (Object termin : termine) { Element terminNode = (Element) termin; resp.getWriter().println("Termin " + index + " : " + terminNode.element("datum").getText() + "<br/>"); resp.getWriter().println("Heim:" + terminNode.element("teama").getText() + "<br/>"); resp.getWriter().println("Gast:" + terminNode.element("teamb").getText() + "<br/>"); resp.getWriter().println("Ergebnis:" + terminNode.element("punkte_a").getText() + ":" + terminNode.element("punkte_b").getText() + "<br/>"); resp.getWriter().println("<br/>"); index++; } resp.getWriter().println(); resp.getWriter().println("</body></html>"); reader.close(); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } catch (DocumentException ex) { throw new RuntimeException(ex); } }
11
Code Sample 1: private void copyFile(File sourceFile, File destFile) throws IOException { if (log.isDebugEnabled()) { log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]"); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
00
Code Sample 1: private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public int[] sort() { boolean t = true; int temp = 0; int[] mas = new int[N]; Random rand = new Random(); for (int i = 0; i < N; i++) { mas[i] = rand.nextInt(10) + 1; } while (t) { t = false; for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { temp = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = temp; t = true; } } } return mas; } Code Sample 2: public Download doDownload(HttpHeader[] headers, URI target) throws HttpRequestException { HttpRequest<E> con = createConnection(HttpMethods.METHOD_GET, target); if (defaultHeaders != null) { putHeaders(con, defaultHeaders); } if (headers != null) { putHeaders(con, headers); } HttpResponse<?> res = execute(con); if (res.getResponseCode() == 200) { return new Download(res); } else { throw new HttpRequestException(res.getResponseCode(), res.getResponseMessage()); } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); }
11
Code Sample 1: private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: public void getZipFiles(String filename) { try { String destinationname = "c:\\mods\\peu\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(filename)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); System.out.println("entryname " + entryName); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
00
Code Sample 1: public static File copyFile(String path) { File src = new File(path); File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } Code Sample 2: public static byte[] read(URL url) throws IOException { byte[] bytes; InputStream is = null; try { is = url.openStream(); bytes = readAllBytes(is); } finally { if (is != null) { is.close(); } } return bytes; }
00
Code Sample 1: protected void saveSelectedFiles() { if (dataList.getSelectedRowCount() == 0) { return; } if (dataList.getSelectedRowCount() == 1) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(dataList.getSelectedRow())); AttachFile entry = (AttachFile) obj; JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(fc.getCurrentDirectory(), entry.getCurrentPath().getName())); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File current = entry.getCurrentPath(); File dest = fc.getSelectedFile(); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return; } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { for (Integer idx : dataList.getSelectedRows()) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(idx)); AttachFile entry = (AttachFile) obj; File current = entry.getCurrentPath(); File dest = new File(fc.getSelectedFile(), entry.getName()); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return; } } Code Sample 2: public void loadJar(final String extName, final String url, final String fileName, final IProgressListener pl) throws Exception { pl.setName(fileName); pl.setProgress(0); pl.setFinished(false); pl.setStarted(true); String installDirName = extDir + File.separator + extName; Log.log("extension installation directory: " + installDirName); File installDir = new File(installDirName); if (!installDir.exists()) { if (!installDir.mkdirs()) { throw new Exception("ExtensionLoader.loadJar: Cannot create install directory: " + installDirName); } } URL downloadURL = new URL(url + fileName); File jarFile = new File(installDirName, fileName); File indexFile = null; long urlTimeStamp = downloadURL.openConnection().getLastModified(); String indexFileName = ""; int idx = fileName.lastIndexOf("."); if (idx > 0) { indexFileName = fileName.substring(0, idx); } else { indexFileName = fileName; } indexFileName = indexFileName + ".idx"; Log.log("index filename: " + indexFileName); boolean isDirty = true; if (jarFile.exists()) { Log.log("extensionfile already exists: " + fileName); indexFile = new File(installDir, indexFileName); if (indexFile.exists()) { Log.log("indexfile already exists"); long cachedTimeStamp = readTimeStamp(indexFile); isDirty = !(cachedTimeStamp == urlTimeStamp); Log.log("cached file dirty: " + isDirty + ", url timestamp: " + urlTimeStamp + " cache stamp: " + cachedTimeStamp); } else { Log.log("indexfile doesn't exist, assume cache is dirty"); } } if (isDirty) { if (jarFile.exists()) { if (indexFile != null && indexFile.exists()) { Log.log("deleting old index file"); indexFile.delete(); } indexFile = new File(installDirName, indexFileName); Log.log("deleting old cached file"); jarFile.delete(); } downloadJar(downloadURL, jarFile, pl); indexFile = new File(installDir, indexFileName); Log.log("writing timestamp to index file"); writeTimeStamp(indexFile, urlTimeStamp); } addJar(jarFile); }
11
Code Sample 1: private String generateUniqueIdMD5(String workgroupIdString, String runIdString) { String passwordUnhashed = workgroupIdString + "-" + runIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(passwordUnhashed.getBytes(), 0, passwordUnhashed.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; } Code Sample 2: public static String md5(String senha) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Ocorreu NoSuchAlgorithmException"); } md.update(senha.getBytes()); byte[] xx = md.digest(); String n2 = null; StringBuffer resposta = new StringBuffer(); for (int i = 0; i < xx.length; i++) { n2 = Integer.toHexString(0XFF & ((int) (xx[i]))); if (n2.length() < 2) { n2 = "0" + n2; } resposta.append(n2); } return resposta.toString(); }
00
Code Sample 1: public void createBankSignature() { byte b; try { _bankMessageDigest = MessageDigest.getInstance("MD5"); _bankSig = Signature.getInstance("MD5/RSA/PKCS#1"); _bankSig.initSign((PrivateKey) _bankPrivateKey); _bankMessageDigest.update(getBankString().getBytes()); _bankMessageDigestBytes = _bankMessageDigest.digest(); _bankSig.update(_bankMessageDigestBytes); _bankSignatureBytes = _bankSig.sign(); } catch (Exception e) { } ; } Code Sample 2: public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void testScenario() throws Exception { String expression = "SELECT id, name, address, phone FROM " + TABLE + " where id > 2 and id < 12 order by id"; SQLQuery query = new SQLQuery(); query.setResourceID(mResourceID); query.addExpression(expression); TupleToWebRowSetCharArrays tupleToWebRowSet = new TupleToWebRowSetCharArrays(); tupleToWebRowSet.connectDataInput(query.getDataOutput()); DeliverToFTP deliverToFTP = new DeliverToFTP(); deliverToFTP.connectDataInput(tupleToWebRowSet.getResultOutput()); deliverToFTP.addFilename(FILE); deliverToFTP.addHost(mURL); PipelineWorkflow pipeline = new PipelineWorkflow(); pipeline.add(query); pipeline.add(tupleToWebRowSet); pipeline.add(deliverToFTP); mDRER.execute(pipeline, RequestExecutionType.SYNCHRONOUS); final URL url = new URL("ftp://" + mURL + "/" + FILE); final URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); InputStream is = connection.getInputStream(); WebRowSetToResultSet converter = new WebRowSetToResultSet(new InputStreamReader(is)); converter.setResultSetType(ResultSet.TYPE_FORWARD_ONLY); ResultSet rs = converter.getResultSet(); JDBCTestHelper.validateResultSet(mConnection, expression, rs, 1); rs.close(); }
00
Code Sample 1: static List<String> listProperties(final MetadataType type) { List<String> props = new ArrayList<String>(); try { File adapter = File.createTempFile("adapter", null); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(type.adapter); if (stream == null) { throw new IllegalStateException("Could not load adapter Jar: " + type.adapter); } FileOutputStream out = new FileOutputStream(adapter); IOUtils.copyLarge(stream, out); out.close(); JarFile jar = new JarFile(adapter); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith("dtd")) { InputStream inputStream = jar.getInputStream(entry); Scanner s = new Scanner(inputStream); while (s.hasNextLine()) { String nextLine = s.nextLine(); if (nextLine.startsWith("<!ELEMENT")) { String prop = nextLine.split(" ")[1]; props.add(prop); } } break; } } } catch (IOException e) { e.printStackTrace(); } return props; } Code Sample 2: private PieceSet[] getPieceSets() { Resource[] resources = boardManager.getResources("pieces"); PieceSet[] pieceSets = new PieceSet[resources.length]; for (int i = 0; i < resources.length; i++) pieceSets[i] = (PieceSet) resources[i]; for (int i = 0; i < resources.length; i++) { for (int j = 0; j < resources.length - (i + 1); j++) { String name1 = pieceSets[j].getName(); String name2 = pieceSets[j + 1].getName(); if (name1.compareTo(name2) > 0) { PieceSet tmp = pieceSets[j]; pieceSets[j] = pieceSets[j + 1]; pieceSets[j + 1] = tmp; } } } return pieceSets; }
00
Code Sample 1: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } Code Sample 2: public static String[] listFilesInJar(String resourcesLstName, String dirPath, String ext) { try { dirPath = Tools.subString(dirPath, "\\", "/"); if (!dirPath.endsWith("/")) { dirPath = dirPath + "/"; } if (dirPath.startsWith("/")) { dirPath = dirPath.substring(1, dirPath.length()); } URL url = ResourceLookup.getClassResourceUrl(Tools.class, resourcesLstName); if (url == null) { String msg = "File not found " + resourcesLstName; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } InputStream is = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String name = in.readLine(); HashSet<String> list = new HashSet<String>(10); while (name != null) { name = in.readLine(); if (name == null) { continue; } if (ext != null && !name.endsWith(ext)) { continue; } if (name.indexOf('.') == -1 && !name.endsWith("/")) { name = name + "/"; } int index = name.indexOf(dirPath); if (index < 0) { continue; } index += dirPath.length(); if (index >= name.length() - 1) { continue; } index = name.indexOf("/", index); if (ext != null && (name.endsWith("/") || index >= 0)) { continue; } else if (ext == null && (index < 0 || index < name.length() - 1)) { continue; } list.add("/" + name); } is.close(); String[] toReturn = {}; return list.toArray(toReturn); } catch (IOException ioe) { String msg = "Error reading file " + resourcesLstName + " caused by " + ioe; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } }
00
Code Sample 1: private void generateSchema() { ConsoleOutputWindow console = DefaultXPontusWindowImpl.getInstance().getConsole(); MessagesWindowDockable mconsole = (MessagesWindowDockable) console.getDockableById(MessagesWindowDockable.DOCKABLE_ID); ByteArrayOutputStream bao = new ByteArrayOutputStream(); IDocumentContainer container = (IDocumentContainer) DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentDockable(); try { SchemaGenerationModel model = view.getModel(); boolean isValid = transformationIsValid(model); if (!isValid) { return; } DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Generating schema..."); view.setVisible(false); InputFormat inFormat = null; OutputFormat of = null; if (model.getInputType().equalsIgnoreCase("RELAX NG Grammar")) { inFormat = new SAXParseInputFormat(); } else if (model.getInputType().equalsIgnoreCase("RELAX NG Compact Grammar")) { inFormat = new CompactParseInputFormat(); } else if (model.getInputType().equalsIgnoreCase("DTD")) { inFormat = new DtdInputFormat(); } else if (model.getInputType().equalsIgnoreCase("XML")) { inFormat = new XmlInputFormat(); } if (model.getOutputType().equalsIgnoreCase("DTD")) { of = new DtdOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("Relax NG Grammar")) { of = new RngOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("XML Schema")) { of = new XsdOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("Relax NG Compact Grammar")) { of = new RncOutputFormat(); } ErrorHandlerImpl eh = new ErrorHandlerImpl(bao); SchemaCollection sc = null; if (!view.getModel().isUseExternalDocument()) { JTextComponent jtc = DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentEditor(); if (jtc == null) { XPontusComponentsUtils.showErrorMessage("No document opened!!!"); DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!"); return; } String suffixe = model.getOutputType().toLowerCase(); File tmp = File.createTempFile("schemageneratorhandler", +System.currentTimeMillis() + "." + suffixe); OutputStream m_outputStream = new FileOutputStream(tmp); CharsetDetector detector = new CharsetDetector(); detector.setText(jtc.getText().getBytes()); Writer m_writer = new OutputStreamWriter(m_outputStream, "UTF-8"); IOUtils.copy(detector.detect().getReader(), m_writer); IOUtils.closeQuietly(m_writer); try { sc = inFormat.load(UriOrFile.toUri(tmp.getAbsolutePath()), new String[0], model.getOutputType().toLowerCase(), eh); } catch (Exception ife) { ife.printStackTrace(); StrBuilder stb = new StrBuilder(); stb.append("\nError loading input document!\n"); stb.append("Maybe the input type is invalid?\n"); stb.append("Please check again the input type list or trying validating your document\n"); throw new Exception(stb.toString()); } tmp.deleteOnExit(); } else { try { sc = inFormat.load(UriOrFile.toUri(view.getModel().getInputURI()), new String[0], model.getOutputType().toLowerCase(), eh); } catch (Exception ife) { StrBuilder stb = new StrBuilder(); stb.append("\nError loading input document!\n"); stb.append("Maybe the input type is invalid?\n"); stb.append("Please check again the input type list or trying validating your document\n"); throw new Exception(stb.toString()); } } OutputDirectory od = new LocalOutputDirectory(sc.getMainUri(), new File(view.getModel().getOutputURI()), model.getOutputType().toLowerCase(), DEFAULT_OUTPUT_ENCODING, DEFAULT_LINE_LENGTH, DEFAULT_INDENT); of.output(sc, od, new String[0], model.getInputType().toLowerCase(), eh); mconsole.println("Schema generated sucessfully!"); DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Schema generated sucessfully!"); if (model.isOpenInEditor()) { XPontusComponentsUtils.showWarningMessage("The document will NOT be opened in the editor sorry for that!\n You need to open it yourself."); } } catch (Exception ex) { DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!"); StringWriter sw = new StringWriter(); PrintWriter ps = new PrintWriter(sw); ex.printStackTrace(ps); StrBuilder sb = new StrBuilder(); sb.append("Error generating schema"); sb.appendNewLine(); sb.append(new String(bao.toByteArray())); sb.appendNewLine(); if (ex instanceof SAXParseException) { SAXParseException spe = (SAXParseException) ex; sb.append("Error around line " + spe.getLineNumber()); sb.append(", column " + spe.getColumnNumber()); sb.appendNewLine(); } sb.append(sw.toString()); mconsole.println(sb.toString(), OutputDockable.RED_STYLE); logger.error(sb.toString()); try { ps.flush(); ps.close(); sw.flush(); sw.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } } finally { console.setFocus(MessagesWindowDockable.DOCKABLE_ID); Toolkit.getDefaultToolkit().beep(); } } Code Sample 2: public GEItem lookup(final String itemName) { try { URL url = new URL(GrandExchange.HOST + "/m=itemdb_rs/results.ws?query=" + itemName + "&price=all&members="); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; while ((input = br.readLine()) != null) { if (input.contains("<div id=\"search_results_text\">")) { input = br.readLine(); if (input.contains("Your search for")) { return null; } } else if (input.startsWith("<td><img src=")) { Matcher matcher = GrandExchange.PATTERN.matcher(input); if (matcher.find()) { if (matcher.group(2).contains(itemName)) { return lookup(Integer.parseInt(matcher.group(1))); } } } } } catch (IOException ignored) { } return null; }
11
Code Sample 1: private void extractSourceFiles(String jar) { JarInputStream in = null; BufferedOutputStream out = null; try { in = new JarInputStream(new FileInputStream(getProjectFile(jar))); JarEntry item; byte buffer[] = new byte[4096]; int buflength; while ((item = in.getNextJarEntry()) != null) if (item.getName().startsWith(PREFIX) && (!item.getName().endsWith("/"))) { out = new BufferedOutputStream(new FileOutputStream(new File(dest, getFileName(item)))); while ((buflength = in.read(buffer)) != -1) out.write(buffer, 0, buflength); howmany++; out.flush(); out.close(); out = null; } } catch (IOException ex) { System.out.println("Unable to parse file " + jar + ", reason: " + ex.getMessage()); } finally { try { if (in != null) in.close(); } catch (IOException ex) { } try { if (out != null) out.close(); } catch (IOException ex) { } } } Code Sample 2: @Override public int onPut(Operation operation) { synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections++; if (logger.isDebugEnabled()) { logger.debug("Connection accepted, total number of connections: " + MuleObexRequestHandler.connections); } } int result = ResponseCodes.OBEX_HTTP_OK; try { headers = operation.getReceivedHeaders(); if (!this.maxFileSize.equals(ObexServer.UNLIMMITED_FILE_SIZE)) { Long fileSize = (Long) headers.getHeader(HeaderSet.LENGTH); if (fileSize == null) { result = ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED; } if (fileSize > this.maxFileSize) { result = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE; } } if (result != ResponseCodes.OBEX_HTTP_OK) { InputStream in = operation.openInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); data = out.toByteArray(); if (interrupted) { data = null; result = ResponseCodes.OBEX_HTTP_GONE; } } return result; } catch (IOException e) { return ResponseCodes.OBEX_HTTP_UNAVAILABLE; } finally { synchronized (this) { this.notify(); } synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections--; if (logger.isDebugEnabled()) { logger.debug("Connection closed, total number of connections: " + MuleObexRequestHandler.connections); } } } }
00
Code Sample 1: public void convert(String newDocumentName, URL url) throws IOException { documentPath = createDirectoryStructure(this.destinationPath, newDocumentName); try { Document doc = builder.build(url.openStream()); Element elementx = doc.getRootElement(); convertElement(elementx); System.out.println("\n\n"); XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat()); System.out.println("as file: " + url.getFile()); File inputFile = new File(url.getFile()); File outputFile = new File(documentPath, renameFileExtention(inputFile, "-remaining.xml")); System.out.println("outputFile: " + outputFile); outp.output(doc, new FileOutputStream(outputFile)); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected GraphicalViewer createGraphicalViewer(Composite parent) { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); GraphicalViewerKeyHandler graphicalViewerKeyHandler = new GraphicalViewerKeyHandler(viewer); KeyHandler parentKeyHandler = graphicalViewerKeyHandler.setParent(getCommonKeyHandler()); viewer.setKeyHandler(parentKeyHandler); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); ContextMenuProvider provider = new TestContextMenuProvider(viewer, getActionRegistry()); viewer.setContextMenu(provider); getSite().registerContextMenu("cubicTestPlugin.editor.contextmenu", provider, viewer); viewer.addDropTargetListener(new DataEditDropTargetListner(((IFileEditorInput) getEditorInput()).getFile().getProject(), viewer)); viewer.addDropTargetListener(new FileTransferDropTargetListener(viewer)); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getContent()); return viewer; }
00
Code Sample 1: public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); } Code Sample 2: private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength - 1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; }
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 boolean start(RootDoc root) { Logger log = Logger.getLogger("DocletGenerator"); if (destination == null) { try { ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8"); String fn = System.getenv("annocultor.xconverter.destination.file.name"); fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn; destination = new File(fn); if (destination.exists()) { destination.delete(); } FileOutputStream os; os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd")); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterTemplate.xsd")), os); os.close(); os = new FileOutputStream(destination); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterInclude.xsd")), os); os.close(); } catch (Exception e) { try { throw new RuntimeException("On destination " + destination.getCanonicalPath(), e); } catch (IOException e1) { throw new RuntimeException(e1); } } } try { String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n"); int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); if (breakPoint < 0) { throw new Exception("Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); } String preambula = s.substring(0, breakPoint); String appendix = s.substring(breakPoint); destination.delete(); PrintWriter schemaWriter = new PrintWriter(destination); schemaWriter.print(preambula); ClassDoc[] classes = root.classes(); for (int i = 0; i < classes.length; ++i) { ClassDoc cd = classes[i]; PrintWriter documentationWriter = null; if (getSuperClasses(cd).contains(Rule.class.getName())) { for (ConstructorDoc constructorDoc : cd.constructors()) { if (constructorDoc.isPublic()) { if (isMeantForXMLAccess(constructorDoc)) { if (documentationWriter == null) { File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml"); documentationWriter = new PrintWriter(file); log.info("Generating doc for rule " + file.getCanonicalPath()); printRuleDocStart(cd, documentationWriter); } boolean initFound = false; for (MethodDoc methodDoc : cd.methods()) { if ("init".equals(methodDoc.name())) { if (methodDoc.parameters().length == 0) { initFound = true; break; } } } if (!initFound) { } printConstructorSchema(constructorDoc, schemaWriter); if (documentationWriter != null) { printConstructorDoc(constructorDoc, documentationWriter); } } } } } if (documentationWriter != null) { printRuleDocEnd(documentationWriter); } } schemaWriter.print(appendix); schemaWriter.close(); log.info("Saved to " + destination.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } return true; }
11
Code Sample 1: public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } } Code Sample 2: public void createZip(String baseDir, String objFileName) throws Exception { logger.info("createZip: [ " + baseDir + "] [" + objFileName + "]"); baseDir = baseDir + "/" + timesmpt; File folderObject = new File(baseDir); if (folderObject.exists()) { List<?> fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName)); ZipEntry ze = null; byte[] buf = new byte[1024]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File f = (File) fileList.get(i); ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); while ((readLen = is.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } is.close(); } zos.close(); } else { throw new Exception("this folder isnot exist!"); } }
00
Code Sample 1: public final void loadAllData(final String ticker, final File output, final CSVFormat outputFormat, final Date from, final Date to) { try { final URL url = buildURL(ticker, from, to); final InputStream is = url.openStream(); final ReadCSV csv = new ReadCSV(is, true, CSVFormat.ENGLISH); final PrintWriter tw = new PrintWriter(new FileWriter(output)); tw.println("date,time,open price,high price,low price," + "close price,volume,adjusted price"); while (csv.next() && !shouldStop()) { final Date date = csv.getDate("date"); final double adjClose = csv.getDouble("adj close"); final double open = csv.getDouble("open"); final double close = csv.getDouble("close"); final double high = csv.getDouble("high"); final double low = csv.getDouble("low"); final double volume = csv.getDouble("volume"); final NumberFormat df = NumberFormat.getInstance(); df.setGroupingUsed(false); final StringBuilder line = new StringBuilder(); line.append(NumericDateUtil.date2Long(date)); line.append(outputFormat.getSeparator()); line.append(NumericDateUtil.time2Int(date)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(open, this.precision)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(high, this.precision)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(low, this.precision)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(close, this.precision)); line.append(outputFormat.getSeparator()); line.append(df.format(volume)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(adjClose, this.precision)); tw.println(line.toString()); } tw.close(); } catch (final IOException ex) { throw new LoaderError(ex); } } Code Sample 2: private boolean goToForum() { URL url = null; URLConnection urlConn = null; int code = 0; boolean gotNumReplies = false; boolean gotMsgNum = false; try { url = new URL("http://" + m_host + "/forums/index.php?topic=" + m_gameId + ".new"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(false); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); m_referer = url.toString(); readCookies(urlConn); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code != 200) { String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = ""; Pattern p_numReplies = Pattern.compile(".*?;num_replies=(\\d+)\".*"); Pattern p_msgNum = Pattern.compile(".*?<a name=\"msg(\\d+)\"></a><a name=\"new\"></a>.*"); Pattern p_attachId = Pattern.compile(".*?action=dlattach;topic=" + m_gameId + ".0;attach=(\\d+)\">.*"); while ((line = in.readLine()) != null) { if (!gotNumReplies) { Matcher match_numReplies = p_numReplies.matcher(line); if (match_numReplies.matches()) { m_numReplies = match_numReplies.group(1); gotNumReplies = true; continue; } } if (!gotMsgNum) { Matcher match_msgNum = p_msgNum.matcher(line); if (match_msgNum.matches()) { m_msgNum = match_msgNum.group(1); gotMsgNum = true; continue; } } Matcher match_attachId = p_attachId.matcher(line); if (match_attachId.matches()) m_attachId = match_attachId.group(1); } in.close(); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotNumReplies || !gotMsgNum) { m_turnSummaryRef = "Error: "; if (!gotNumReplies) m_turnSummaryRef += "No num_replies found in A&A.org forum topic. "; if (!gotMsgNum) m_turnSummaryRef += "No msgXXXXXX found in A&A.org forum topic. "; return false; } return true; }
00
Code Sample 1: protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); } Code Sample 2: public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
00
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } } if (destination != null) { destination.close(); } } Code Sample 2: public static int getUrl(final String s) { try { final URL url = new URL(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); int count = 0; String data = null; while ((data = reader.readLine()) != null) { System.out.printf("Results(%3d) of data: %s\n", count, data); ++count; } return count; } catch (Exception ex) { throw new RuntimeException(ex); } }
11
Code Sample 1: public void handleRequestInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { final String servetPath = httpServletRequest.getServletPath(); final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH); final String currentToken = getETagValue(httpServletRequest); httpServletResponse.setHeader(ETAG, currentToken); final Date modifiedDate = new Date(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE)); final Calendar calendar = Calendar.getInstance(); final Date now = calendar.getTime(); calendar.setTime(modifiedDate); calendar.add(Calendar.MINUTE, getEtagExpiration()); if (currentToken.equals(previousToken) && (now.getTime() < calendar.getTime().getTime())) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED); httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE)); if (LOG.isDebugEnabled()) { LOG.debug("ETag the same, will return 304"); } } else { httpServletResponse.setDateHeader(LAST_MODIFIED, (new Date()).getTime()); final String width = httpServletRequest.getParameter(Constants.WIDTH); final String height = httpServletRequest.getParameter(Constants.HEIGHT); final ImageNameStrategy imageNameStrategy = imageService.getImageNameStrategy(servetPath); String code = imageNameStrategy.getCode(servetPath); String fileName = imageNameStrategy.getFileName(servetPath); final String imageRealPathPrefix = getRealPathPrefix(httpServletRequest.getServerName().toLowerCase()); String original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); final File origFile = new File(original); if (!origFile.exists()) { code = Constants.NO_IMAGE; fileName = imageNameStrategy.getFileName(code); original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); } String resizedImageFileName = null; if (width != null && height != null && imageService.isSizeAllowed(width, height)) { resizedImageFileName = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code, width, height); } final File imageFile = getImageFile(original, resizedImageFileName, width, height); final FileInputStream fileInputStream = new FileInputStream(imageFile); IOUtils.copy(fileInputStream, httpServletResponse.getOutputStream()); fileInputStream.close(); } } Code Sample 2: private void insertContent(ImageData imageData, Element element) { URL url = getClass().getResource(imageData.getURL()); try { File imageFileRead = new File(url.toURI()); FileInputStream inputStream = new FileInputStream(imageFileRead); String imageFileWritePath = "htmlReportFiles" + "/" + imageData.getURL(); File imageFileWrite = new File(imageFileWritePath); String[] filePathTokens = imageFileWritePath.split("/"); String directoryPathCreate = filePathTokens[0]; int i = 1; while (i < filePathTokens.length - 1) { directoryPathCreate = directoryPathCreate + "/" + filePathTokens[i]; i++; } File fileDirectoryPathCreate = new File(directoryPathCreate); if (!fileDirectoryPathCreate.exists()) { boolean successfulFileCreation = fileDirectoryPathCreate.mkdirs(); if (successfulFileCreation == false) { throw new ExplanationException("Unable to create folders in path " + directoryPathCreate); } } FileOutputStream fileOutputStream = new FileOutputStream(imageFileWrite); byte[] data = new byte[1024]; int readDataNumberOfBytes = 0; while (readDataNumberOfBytes != -1) { readDataNumberOfBytes = inputStream.read(data, 0, data.length); if (readDataNumberOfBytes != -1) { fileOutputStream.write(data, 0, readDataNumberOfBytes); } } inputStream.close(); fileOutputStream.close(); } catch (Exception ex) { throw new ExplanationException(ex.getMessage()); } String caption = imageData.getCaption(); Element imageElement = element.addElement("img"); if (imageData.getURL().charAt(0) != '/') imageElement.addAttribute("src", "htmlReportFiles" + "/" + imageData.getURL()); else imageElement.addAttribute("src", "htmlReportFiles" + imageData.getURL()); imageElement.addAttribute("alt", "image not available"); if (caption != null) { element.addElement("br"); element.addText(caption); } }
11
Code Sample 1: private String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); } Code Sample 2: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
00
Code Sample 1: Object onSuccess() { this.mErrorExist = true; this.mErrorMdp = true; if (this.mNewMail.equals(mClient.getEmail()) || !this.mNewMail.equals(mClient.getEmail()) && !mClientManager.exists(this.mNewMail)) { this.mErrorExist = false; if (mNewMdp != null && mNewMdpConfirm != null) { if (this.mNewMdp.equals(this.mNewMdpConfirm)) { this.mErrorMdp = false; MessageDigest sha1Instance; try { sha1Instance = MessageDigest.getInstance("SHA1"); sha1Instance.reset(); sha1Instance.update(this.mNewMdp.getBytes()); byte[] digest = sha1Instance.digest(); BigInteger bigInt = new BigInteger(1, digest); String vHashPassword = bigInt.toString(16); mClient.setMdp(vHashPassword); } catch (NoSuchAlgorithmException e) { mLogger.error(e.getMessage(), e); } } } else { this.mErrorMdp = false; } if (!this.mErrorMdp) { mClient.setAdresse(this.mNewAdresse); mClient.setEmail(this.mNewMail); mClient.setNom(this.mNewNom); mClient.setPrenom((this.mNewPrenom != null ? this.mNewPrenom : "")); Client vClient = new Client(mClient); mClientManager.save(vClient); mComponentResources.discardPersistentFieldChanges(); return "Client/List"; } } return errorZone.getBody(); } Code Sample 2: public synchronized FTPClient getFTPClient(String User, String Password) throws IOException { if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - start"); } while ((counter >= maxClients)) { try { wait(); } catch (InterruptedException e) { logger.error("getFTPClient(String, String)", e); e.printStackTrace(); } } FTPClient result = null; String key = User.concat(Password); logger.debug("versuche vorhandenen FTPClient aus Liste zu lesen"); if (Clients != null) { if (Clients.containsKey(key)) { LinkedList ClientList = (LinkedList) Clients.get(key); if (!ClientList.isEmpty()) do { result = (FTPClient) ClientList.getLast(); logger.debug("-- hole einen Client aus der Liste: " + result.toString()); ClientList.removeLast(); if (!result.isConnected()) { logger.debug("---- nicht mehr verbunden."); result = null; } else { try { result.changeWorkingDirectory("/"); } catch (IOException e) { logger.debug("---- schmei�t Exception bei Zugriff."); result = null; } } } while (result == null && !ClientList.isEmpty()); if (ClientList.isEmpty()) { Clients.remove(key); } } else { } } else logger.debug("-- keine Liste vorhanden."); if (result == null) { logger.debug("Kein FTPCLient verf�gbar, erstelle einen neuen."); result = new FTPClient(); logger.debug("-- Versuche Connect"); result.connect(Host); logger.debug("-- Versuche Login"); result.login(User, Password); result.setFileType(FTPClient.BINARY_FILE_TYPE); if (counter == maxClients - 1) { RemoveBufferedClient(); } } logger.debug("OK: neuer FTPClient ist " + result.toString()); ; counter++; if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - end"); } return result; }
00
Code Sample 1: public String genPass() { String salto = "Z1mX502qLt2JTcW9MTDTGBBw8VBQQmY2"; String clave = (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10); password = clave; String claveConSalto = clave + salto; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); m.update(claveConSalto.getBytes("utf-8"), 0, claveConSalto.length()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String claveCifrada = new BigInteger(1, m.digest()).toString(16); return claveCifrada + ":" + salto; } Code Sample 2: private static void writeBinaryFile(String filename, String target) throws IOException { File outputFile = new File(target); AgentFilesystem.forceDir(outputFile.getParent()); FileOutputStream output = new FileOutputStream(new File(target)); FileInputStream inputStream = new FileInputStream(filename); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > -1) output.write(buffer, 0, bytesRead); inputStream.close(); output.close(); }
11
Code Sample 1: private void populateAPI(API api) { try { if (api.isPopulated()) { log.traceln("Skipping API " + api.getName() + " (already populated)"); return; } api.setPopulated(true); String sql = "update API set populated=1 where name=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, api.getName()); pstmt.executeUpdate(); pstmt.close(); storePackagesAndClasses(api); conn.commit(); } catch (SQLException ex) { log.error("Store (api: " + api.getName() + ") failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } } Code Sample 2: protected PTask commit_result(Result r, SyrupConnection con) throws Exception { try { int logAction = LogEntry.ENDED; String kk = r.context().task().key(); if (r.in_1_consumed() && r.context().in_1_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, false, null, con); logAction = logAction | LogEntry.IN_1; } if (r.in_2_consumed() && r.context().in_2_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, true, null, con); logAction = logAction | LogEntry.IN_2; } if (r.out_1_result() != null && r.context().out_1_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, false, r.out_1_result(), con); logAction = logAction | LogEntry.OUT_1; } if (r.out_2_result() != null && r.context().out_2_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, true, r.out_2_result(), con); logAction = logAction | LogEntry.OUT_2; } sqlImpl().loggingFunctions().log(r.context().task().key(), logAction, con); boolean isParent = r.context().task().isParent(); if (r instanceof Workflow) { Workflow w = (Workflow) r; Task[] tt = w.tasks(); Link[] ll = w.links(); Hashtable tkeyMap = new Hashtable(); for (int i = 0; i < tt.length; i++) { String key = sqlImpl().creationFunctions().newTask(tt[i], r.context().task(), con); tkeyMap.put(tt[i], key); } for (int j = 0; j < ll.length; j++) { sqlImpl().creationFunctions().newLink(ll[j], tkeyMap, con); } String in_link_1 = sqlImpl().queryFunctions().readInTask(kk, false, con); String in_link_2 = sqlImpl().queryFunctions().readInTask(kk, true, con); String out_link_1 = sqlImpl().queryFunctions().readOutTask(kk, false, con); String out_link_2 = sqlImpl().queryFunctions().readOutTask(kk, true, con); sqlImpl().updateFunctions().rewireInLink(kk, false, w.in_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireInLink(kk, true, w.in_2_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, false, w.out_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, true, w.out_2_binding(), tkeyMap, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateDone(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateDone(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_2, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_2, con); isParent = true; } sqlImpl().updateFunctions().checkAndUpdateDone(kk, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kk, con); PreparedStatement s3 = null; s3 = con.prepareStatementFromCache(sqlImpl().sqlStatements().updateTaskModificationStatement()); java.util.Date dd = new java.util.Date(); s3.setLong(1, dd.getTime()); s3.setBoolean(2, isParent); s3.setString(3, r.context().task().key()); s3.executeUpdate(); sqlImpl().loggingFunctions().log(kk, LogEntry.ENDED, con); con.commit(); return sqlImpl().queryFunctions().readPTask(kk, con); } finally { con.rollback(); } }
00
Code Sample 1: private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; BOTLRuleDiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((BOTLRuleDiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
00
Code Sample 1: public static String hashMD5(String passw) { String passwHash = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passw.getBytes()); byte[] result = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String tmpStr = "0" + Integer.toHexString((0xff & result[i])); sb.append(tmpStr.substring(tmpStr.length() - 2)); } passwHash = sb.toString(); } catch (NoSuchAlgorithmException ecc) { log.error("Errore algoritmo " + ecc); } return passwHash; } Code Sample 2: private void alterarCategoria(Categoria cat) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE categoria SET nome_categoria = ? where id_categoria = ?"; ps = conn.prepareStatement(sql); ps.setString(1, cat.getNome()); ps.setInt(2, cat.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
11
Code Sample 1: public static boolean writeFileB2C(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pIs, fw); fw.flush(); fw.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; }
00
Code Sample 1: private void loadOperatorsXML() { startwindow.setMessage("Loading Operators..."); try { URL url = Application.class.getClassLoader().getResource(Resources.getString("OPERATORS_XML")); InputStream input = url.openStream(); OperatorsReader.registerOperators(Resources.getString("OPERATORS_XML"), input); } catch (FileNotFoundException e) { Logger.logException("File '" + Resources.getString("OPERATORS_XML") + "' not found.", e); } catch (IOException error) { Logger.logException(error.getMessage(), error); } } Code Sample 2: private static void doCopyFile(FileInputStream in, FileOutputStream out) { FileChannel inChannel = null, outChannel = null; try { inChannel = in.getChannel(); outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw ManagedIOException.manage(e); } finally { if (inChannel != null) { close(inChannel); } if (outChannel != null) { close(outChannel); } } }
00
Code Sample 1: private String generateHash(String key, String data) throws ChiropteraException { try { MessageDigest md = MessageDigest.getInstance(Constants.Connection.Auth.MD5); md.update(key.getBytes()); byte[] raw = md.digest(); String s = toHexString(raw); SecretKey skey = new SecretKeySpec(s.getBytes(), Constants.Connection.Auth.HMACMD5); Mac mac = Mac.getInstance(skey.getAlgorithm()); mac.init(skey); byte digest[] = mac.doFinal(data.getBytes()); String digestB64 = BaculaBase64.binToBase64(digest); return digestB64.substring(0, digestB64.length()); } catch (NoSuchAlgorithmException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } catch (InvalidKeyException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } } Code Sample 2: public void save(String oid, String key, Serializable obj) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { byte[] data = serialize(obj); conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _data_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length); ps.setLong(2, System.currentTimeMillis()); ps.setString(3, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to save object: OID = " + oid, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
11
Code Sample 1: public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); } 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 static void copyFile(File src, File dst) throws IOException { FileChannel sourceChannel = new FileInputStream(src).getChannel(); FileChannel destinationChannel = new FileOutputStream(dst).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
00
Code Sample 1: public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
00
Code Sample 1: public static void sortSeries(double[] series) { if (series == null) { throw new IllegalArgumentException("Incorrect series. It's null-pointed"); } int k = 0; int right = series.length - 1; while (right > 0) { k = 0; for (int i = 0; i <= right - 1; i++) { if (series[i] > series[i + 1]) { k = i; double tmp = series[i]; series[i] = series[i + 1]; series[i + 1] = tmp; } } right = k; } } Code Sample 2: public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); }
00
Code Sample 1: public synchronized void checkout() throws SQLException, InterruptedException { Connection con = this.session.open(); con.setAutoCommit(false); String sql_stmt = DB2SQLStatements.shopping_cart_getAll(this.customer_id); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet res = stmt.executeQuery(sql_stmt); res.last(); int rowcount = res.getRow(); res.beforeFirst(); ShoppingCartItem[] resArray = new ShoppingCartItem[rowcount]; int i = 0; while (res.next()) { resArray[i] = new ShoppingCartItem(); resArray[i].setCustomer_id(res.getInt("customer_id")); resArray[i].setDate_start(res.getDate("date_start")); resArray[i].setDate_stop(res.getDate("date_stop")); resArray[i].setRoom_type_id(res.getInt("room_type_id")); resArray[i].setNumtaken(res.getInt("numtaken")); resArray[i].setTotal_price(res.getInt("total_price")); i++; } this.wait(4000); try { for (int j = 0; j < rowcount; j++) { sql_stmt = DB2SQLStatements.room_date_update(resArray[j]); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } } catch (SQLException e) { e.printStackTrace(); con.rollback(); } for (int j = 0; j < rowcount; j++) { System.out.println(j); sql_stmt = DB2SQLStatements.booked_insert(resArray[j], 2); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } sql_stmt = DB2SQLStatements.shopping_cart_deleteAll(this.customer_id); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); con.commit(); this.session.close(con); } Code Sample 2: private static boolean unzipWithWarning(File source, File targetDirectory, OverwriteValue policy) { try { if (!source.exists()) return false; ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; byte[] buffer = new byte[1024]; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; File newFile = new File(targetDirectory, zipEntry.getName()); if (newFile.exists()) { switch(policy.value) { case NO_TO_ALL: continue; case YES_TO_ALL: break; default: switch(policy.value = confirmOverwrite(zipEntry.getName())) { case NO_TO_ALL: case NO: continue; default: } } } newFile.getParentFile().mkdirs(); int bytesRead; FileOutputStream output = new FileOutputStream(newFile); while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.closeEntry(); } input.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public java.io.File gzip(java.io.File file) throws Exception { java.io.File tmp = null; InputStream is = null; OutputStream os = null; try { tmp = java.io.File.createTempFile(file.getName(), ".gz"); tmp.deleteOnExit(); is = new BufferedInputStream(new FileInputStream(file)); os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(tmp))); byte[] buf = new byte[4096]; int nread = -1; while ((nread = is.read(buf)) != -1) { os.write(buf, 0, nread); } os.flush(); } finally { os.close(); is.close(); } return tmp; }
00
Code Sample 1: public void extractImage(String input, OutputStream os, DjatokaDecodeParam params, IWriter w) throws DjatokaException { File in = null; if (input.equals(STDIN)) { try { in = File.createTempFile("tmp", ".jp2"); input = in.getAbsolutePath(); in.deleteOnExit(); IOUtils.copyFile(new File(STDIN), in); } catch (IOException e) { logger.error("Unable to process image from " + STDIN + ": " + e.getMessage()); throw new DjatokaException(e); } } BufferedImage bi = extractImpl.process(input, params); if (bi != null) { if (params.getScalingFactor() != 1.0 || params.getScalingDimensions() != null) bi = applyScaling(bi, params); if (params.getTransform() != null) bi = params.getTransform().run(bi); w.write(bi, os); } if (in != null) in.delete(); } Code Sample 2: private byte[] getCharImage(long chrId) { byte[] imgData = null; try { URL url = new URL("http://img.eve.is/serv.asp?s=256&c=" + chrId); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); int data; try { while ((data = is.read()) >= 0) { os.write(data); } } finally { is.close(); } imgData = os.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return imgData; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel inputFileChannel = new FileInputStream(sourceFile).getChannel(); FileChannel outputFileChannel = new FileOutputStream(destFile).getChannel(); long offset = 0L; long length = inputFileChannel.size(); final long MAXTRANSFERBUFFERLENGTH = 1024 * 1024; try { for (; offset < length; ) { offset += inputFileChannel.transferTo(offset, MAXTRANSFERBUFFERLENGTH, outputFileChannel); inputFileChannel.position(offset); } } finally { try { outputFileChannel.close(); } catch (Exception ignore) { } try { inputFileChannel.close(); } catch (IOException ignore) { } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; } Code Sample 2: public String getChallengers() { InputStream is = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return "none"; } else return result; } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return "none"; }
00
Code Sample 1: public CServletContextWrapper(final FileSystem fs, final String contextName) { this.fs = fs; this.name = contextName; CContext.getInstance().init(this); try { URL url = this.getResource("/WEB-INF/classes/log4j.properties"); boolean ok = false; InputStream in = null; try { in = url.openStream(); ok = true; } catch (Throwable e) { } finally { try { if (in != null) in.close(); } catch (Exception ignore) { } } if (ok) { PropertyConfigurator.configure(url); } } catch (final Throwable e) { if (!hasPrintedLog4JWarning) { hasPrintedLog4JWarning = true; System.err.println("!!! WARNING: /WEB-INF/classes/log4j.properties missing."); } } this.init(); this.loadServletContextListener(); this.log = LOGGERHelper.getLogger(this.getClass()); CJNDIContextSetup.init(this); JDBCPooler.init(this); CResourceBundle.registerBundles(this); this.fireInitEvent(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static byte[] findHead(String url) { byte[] result = new byte[0]; InputStream in = null; try { in = new URL(appendSlash(url)).openStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = in.read(buffer)) != -1) { byte[] temp = new byte[result.length + len]; System.arraycopy(result, 0, temp, 0, result.length); System.arraycopy(buffer, 0, temp, result.length, len); result = temp; if (DEBUG) { log.debug(String.format("len=%d, result.length=%d", len, result.length)); } if (result.length > 4096) { break; } if (result.length > 1024) { String s = new String(result).replaceAll("\\s+", " "); Matcher m = P_HEAD.matcher(s); if (m.find()) { break; } } } } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { if (null != in) in.close(); } catch (IOException e) { } } return result; } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: public static String loadUrlContentAsString(URL url) throws IOException { char[] buf = new char[2048]; StringBuffer ret = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); for (int chars = reader.read(buf); chars != -1; chars = reader.read(buf)) { ret.append(buf, 0, chars); } reader.close(); return ret.toString(); } Code Sample 2: public void render(HttpServletRequest request, HttpServletResponse response, File file, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } if (file.length() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Cannot send file greater than 2GB"); } response.setContentLength((int) file.length()); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); }
11
Code Sample 1: public void 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: protected String encrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PublicKey pk = getPublicKey(key); if (pk == null) { throw new CryptographicFailureException("PublicKeyNotFound", String.format("Cannot find public key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(data.getBytes()); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(Base64.encodeBase64(bout.toByteArray())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
00
Code Sample 1: private static boolean tryExpandGorillaHome(File f) throws GorillaHomeException { if (f.exists()) { if (!f.isDirectory() || !f.canWrite()) { return false; } } else { boolean dirOK = f.mkdirs(); } if (f.exists() && f.isDirectory() && f.canWrite()) { java.net.URL url = GorillaHome.class.getResource("/resource_defaults/GORILLA_HOME"); if (url == null) { throw new GorillaHomeException("cannot find gorilla.home resources relative to class " + GorillaHome.class.getName()); } java.net.URLConnection conn; try { conn = url.openConnection(); } catch (IOException e) { String msg = "Error opening connection to " + url.toString(); logger.error(msg, e); throw new GorillaHomeException("Error copying " + url.toString(), e); } if (conn == null) { throw new GorillaHomeException("cannot find gorilla.home resources relative to class " + GorillaHome.class.getName()); } if (conn instanceof java.net.JarURLConnection) { logger.debug("Expanding gorilla.home from from jar file via url " + url.toString()); try { IOUtil.expandJar((java.net.JarURLConnection) conn, f); return true; } catch (Exception e) { throw new GorillaHomeException("Error expanding gorilla.home" + " from jar file at " + conn.getURL().toString() + ": " + e.getMessage()); } } else { try { IOUtil.copyDir(new File(url.getFile()), f); return true; } catch (Exception e) { throw new GorillaHomeException("Error expanding gorilla.home" + " from file at " + conn.getURL().toString() + ": " + e.getMessage()); } } } return false; } Code Sample 2: public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("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 bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: @SuppressWarnings("unchecked") private void doService(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String url = request.getRequestURL().toString(); if (url.endsWith("/favicon.ico")) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (url.contains("/delay")) { final String delay = StringUtils.substringBetween(url, "/delay", "/"); final int ms = Integer.parseInt(delay); if (LOG.isDebugEnabled()) { LOG.debug("Sleeping for " + ms + " before to deliver " + url); } Thread.sleep(ms); } final URL requestedUrl = new URL(url); final WebRequest webRequest = new WebRequest(requestedUrl); webRequest.setHttpMethod(HttpMethod.valueOf(request.getMethod())); for (final Enumeration<String> en = request.getHeaderNames(); en.hasMoreElements(); ) { final String headerName = en.nextElement(); final String headerValue = request.getHeader(headerName); webRequest.setAdditionalHeader(headerName, headerValue); } final List<NameValuePair> requestParameters = new ArrayList<NameValuePair>(); for (final Enumeration<String> paramNames = request.getParameterNames(); paramNames.hasMoreElements(); ) { final String name = paramNames.nextElement(); final String[] values = request.getParameterValues(name); for (final String value : values) { requestParameters.add(new NameValuePair(name, value)); } } if ("PUT".equals(request.getMethod()) && request.getContentLength() > 0) { final byte[] buffer = new byte[request.getContentLength()]; request.getInputStream().readLine(buffer, 0, buffer.length); webRequest.setRequestBody(new String(buffer)); } else { webRequest.setRequestParameters(requestParameters); } final WebResponse resp = MockConnection_.getResponse(webRequest); response.setStatus(resp.getStatusCode()); for (final NameValuePair responseHeader : resp.getResponseHeaders()) { response.addHeader(responseHeader.getName(), responseHeader.getValue()); } if (WriteContentAsBytes_) { IOUtils.copy(resp.getContentAsStream(), response.getOutputStream()); } else { final String newContent = getModifiedContent(resp.getContentAsString()); final String contentCharset = resp.getContentCharset(); response.setCharacterEncoding(contentCharset); response.getWriter().print(newContent); } response.flushBuffer(); } Code Sample 2: private InputStream connectURL(String aurl) throws IOException { InputStream in = null; int response = -1; URL url = new URL(aurl); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection."); HttpURLConnection httpConn = (HttpURLConnection) conn; response = getResponse(httpConn); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } else throw new IOException("Response Code: " + response); return in; }
00
Code Sample 1: private Properties loadDefaultProperties() throws IOException { Properties merged = new Properties(); try { merged.setProperty("user", System.getProperty("user.name")); } catch (java.lang.SecurityException se) { } ClassLoader cl = getClass().getClassLoader(); if (cl == null) cl = ClassLoader.getSystemClassLoader(); if (cl == null) { logger.debug("Can't find a classloader for the Driver; not loading driver configuration"); return merged; } logger.debug("Loading driver configuration via classloader " + cl); ArrayList urls = new ArrayList(); Enumeration urlEnum = cl.getResources("org/postgresql/driverconfig.properties"); while (urlEnum.hasMoreElements()) { urls.add(urlEnum.nextElement()); } for (int i = urls.size() - 1; i >= 0; i--) { URL url = (URL) urls.get(i); logger.debug("Loading driver configuration from: " + url); InputStream is = url.openStream(); merged.load(is); is.close(); } return merged; } Code Sample 2: protected BufferedImage handleNLIBException() { if (params.uri.startsWith("http://digar.nlib.ee/otsing/") || params.uri.startsWith("http://digar.nlib.ee/show")) try { String url = "http://digar.nlib.ee/gmap/nd" + params.uri.substring(params.uri.indexOf(":") + 1, params.uri.lastIndexOf("&")) + "-tiles/z0x0y0.jpeg"; URLConnection connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e) { try { if (params.uri.startsWith("http://digar.nlib.ee/show")) params.uri = "http://digar.nlib.ee/otsing/?pid=" + params.uri.substring(params.uri.lastIndexOf("/") + 1) + "&show"; URLConnection connection = new URL(params.uri).openConnection(); String url = params.uri; if (url.endsWith("&show")) url = url.substring(0, url.length() - 5); int index = url.lastIndexOf("?"); url = "stream" + url.substring(index); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String aux = null; while ((aux = reader.readLine()) != null) { index = aux.indexOf(url); if (index != -1) { url = "http://digar.nlib.ee/otsing/" + aux.substring(index); index = url.indexOf('>'); if (index == -1) index = url.indexOf("\""); url = url.substring(0, index); break; } } connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e2) { } } return null; }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; }
11
Code Sample 1: public static void main(String[] args) { try { { byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1)); System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1)); byte[] dbytes = decode(encodeBytes(bytes1)); System.out.print(encodeBytes(bytes1) + " decoded: "); for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n")); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); byte[] bytes = new byte[0]; int b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, temp, 0, bytes.length); temp[bytes.length] = (byte) b; bytes = temp; } b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); fos.write(bytes); fos.close(); fis = new java.io.FileInputStream("test.gif_out"); b64is = new Base64.InputStream(fis, ENCODE); byte[] ebytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[ebytes.length + 1]; System.arraycopy(ebytes, 0, temp, 0, ebytes.length); temp[ebytes.length] = (byte) b; ebytes = temp; } b64is.close(); String s = new String(ebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif_out"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif.b64_out"); fos.write(ebytes); fis = new java.io.FileInputStream("test.gif.b64_out"); b64is = new Base64.InputStream(fis, DECODE); byte[] edbytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[edbytes.length + 1]; System.arraycopy(edbytes, 0, temp, 0, edbytes.length); temp[edbytes.length] = (byte) b; edbytes = temp; } b64is.close(); iicon = new javax.swing.ImageIcon(edbytes); jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); byte[] rbytes = new byte[0]; int b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rbytes.length + 1]; System.arraycopy(rbytes, 0, temp, 0, rbytes.length); temp[rbytes.length] = (byte) b; rbytes = temp; } fis.close(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE); b64os.write(rbytes); b64os.close(); fis = new java.io.FileInputStream("test.gif.b64_out2"); byte[] rebytes = new byte[0]; b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rebytes.length + 1]; System.arraycopy(rebytes, 0, temp, 0, rebytes.length); temp[rebytes.length] = (byte) b; rebytes = temp; } fis.close(); String s = new String(rebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif.b64_out2"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream(fos, DECODE); b64os.write(rebytes); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while ((b = b64is.read()) >= 0) fos.write(b); fos.close(); b64is.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (doAuth(request, response)) { Connection conn = null; try { int UID = icsm.getIntChatSession(request).getUID(); conn = getJDBCConnection(icsm.getHeavyDatabaseConnectionPool(), request, response, HttpServletResponse.SC_SERVICE_UNAVAILABLE); if (conn == null) return; ResultSet rs = IntChatDatabaseOperations.executeQuery(conn, "SELECT id FROM ic_messagetypes WHERE templatename='" + IntChatConstants.MessageTemplates.IC_FILES + "' LIMIT 1"); if (rs.next()) { int fileTypeID = rs.getInt("id"); String recipients = request.getHeader(IntChatConstants.HEADER_FILERECIPIENTS); rs.getStatement().close(); rs = null; if (recipients != null) { HashMap<String, String> hm = Tools.parseMultiparamLine(request.getHeader("Content-Disposition")); String fileName = URLDecoder.decode(hm.get("filename"), IntChatServerDefaults.ENCODING); long fileLength = (request.getHeader("Content-Length") != null ? Long.parseLong(request.getHeader("Content-Length")) : -1); fileLength = (request.getHeader(IntChatConstants.HEADER_FILELENGTH) != null ? Long.parseLong(request.getHeader(IntChatConstants.HEADER_FILELENGTH)) : fileLength); long maxFileSize = RuntimeParameters.getIntValue(ParameterNames.MAX_FILE_SIZE) * 1048576; if (maxFileSize > 0 && fileLength > maxFileSize) { request.getInputStream().close(); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } long now = System.currentTimeMillis(); long nextid = ic_messages_id_seq.nextval(); IntChatServletInputStream in = new IntChatServletInputStream(request); IntChatMessage icm = null; conn.setAutoCommit(false); try { PreparedStatement ps = conn.prepareStatement("INSERT INTO ic_messages (id, tid, mhead, mbody, mdate, sid) VALUES (?, ?, ?, ?, ?, ?)"); ps.setLong(1, nextid); ps.setInt(2, fileTypeID); ps.setString(3, fileName); ps.setString(4, Long.toString(fileLength)); ps.setLong(5, now); ps.setInt(6, UID); ps.executeUpdate(); ps.close(); if (!insertBLOB(conn, in, fileLength, nextid, maxFileSize)) { conn.rollback(); return; } icm = new IntChatMessage(false, fileTypeID, null, null); String[] id = recipients.split(","); int id1; for (int i = 0; i < id.length; i++) { id1 = Integer.parseInt(id[i].trim()); IntChatDatabaseOperations.executeUpdate(conn, "INSERT INTO ic_recipients (mid, rid) VALUES ('" + nextid + "', '" + id1 + "')"); icm.addTo(id1); } conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } if (icm != null) { icm.setID(nextid); icm.setDate(new Timestamp(now - TimeZone.getDefault().getOffset(now))); icm.setFrom(UID); icm.setHeadText(fileName); icm.setBodyText(Long.toString(fileLength)); icsm.onClientSentMessage(icm); } response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } if (rs != null) { rs.getStatement().close(); rs = null; } } catch (RetryRequest rr) { throw rr; } catch (Exception e) { Tools.makeErrorResponse(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { try { if (conn != null) icsm.getHeavyDatabaseConnectionPool().releaseConnection(conn); } catch (Exception e) { } } } } Code Sample 2: public static String deleteTag(String tag_id) { String so = OctopusErrorMessages.UNKNOWN_ERROR; if (tag_id == null || tag_id.trim().equals("")) { return OctopusErrorMessages.TAG_ID_CANT_BE_EMPTY; } DBConnection theConnection = null; try { theConnection = DBServiceManager.allocateConnection(); theConnection.setAutoCommit(false); String query = "DELETE FROM tr_translation WHERE tr_translation_trtagid=?"; PreparedStatement state = theConnection.prepareStatement(query); state.setString(1, tag_id); state.executeUpdate(); String query2 = "DELETE FROM tr_tag WHERE tr_tag_id=? "; PreparedStatement state2 = theConnection.prepareStatement(query2); state2.setString(1, tag_id); state2.executeUpdate(); theConnection.commit(); so = OctopusErrorMessages.ACTION_DONE; } catch (SQLException e) { try { theConnection.rollback(); } catch (SQLException ex) { } so = OctopusErrorMessages.ERROR_DATABASE; } finally { if (theConnection != null) { try { theConnection.setAutoCommit(true); } catch (SQLException ex) { } theConnection.release(); } } return so; }
11
Code Sample 1: public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } } Code Sample 2: private boolean saveLOBDataToFileSystem() { if ("".equals(m_attachmentPathRoot)) { log.severe("no attachmentPath defined"); return false; } if (m_items == null || m_items.size() == 0) { setBinaryData(null); return true; } final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement("attachments"); document.appendChild(root); document.setXmlStandalone(true); for (int i = 0; i < m_items.size(); i++) { log.fine(m_items.get(i).toString()); File entryFile = m_items.get(i).getFile(); final String path = entryFile.getAbsolutePath(); log.fine(path + " - " + m_attachmentPathRoot); if (!path.startsWith(m_attachmentPathRoot)) { log.fine("move file: " + path); FileChannel in = null; FileChannel out = null; try { final File destFolder = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet()); if (!destFolder.exists()) { if (!destFolder.mkdirs()) { log.warning("unable to create folder: " + destFolder.getPath()); } } final File destFile = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); in = new FileInputStream(entryFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); if (entryFile.exists()) { if (!entryFile.delete()) { entryFile.deleteOnExit(); } } entryFile = destFile; } catch (IOException e) { e.printStackTrace(); log.severe("unable to copy file " + entryFile.getAbsolutePath() + " to " + m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); } finally { if (in != null && in.isOpen()) { in.close(); } if (out != null && out.isOpen()) { out.close(); } } } final Element entry = document.createElement("entry"); entry.setAttribute("name", getEntryName(i)); String filePathToStore = entryFile.getAbsolutePath(); filePathToStore = filePathToStore.replaceFirst(m_attachmentPathRoot.replaceAll("\\\\", "\\\\\\\\"), ATTACHMENT_FOLDER_PLACEHOLDER); log.fine(filePathToStore); entry.setAttribute("file", filePathToStore); root.appendChild(entry); } final Source source = new DOMSource(document); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Result result = new StreamResult(bos); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); final byte[] xmlData = bos.toByteArray(); log.fine(bos.toString()); setBinaryData(xmlData); return true; } catch (Exception e) { log.log(Level.SEVERE, "saveLOBData", e); } setBinaryData(null); return false; }
11
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: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: @Override public void handle(HttpExchange http) throws IOException { Headers reqHeaders = http.getRequestHeaders(); Headers respHeader = http.getResponseHeaders(); respHeader.add("Content-Type", "text/plain"); http.sendResponseHeaders(200, 0); PrintWriter console = new PrintWriter(System.err); PrintWriter web = new PrintWriter(http.getResponseBody()); PrintWriter out = new PrintWriter(new YWriter(web, console)); out.println("### " + new Date() + " ###"); out.println("Method: " + http.getRequestMethod()); out.println("Protocol: " + http.getProtocol()); out.println("RemoteAddress.HostName: " + http.getRemoteAddress().getHostName()); for (String key : reqHeaders.keySet()) { out.println("* \"" + key + "\""); for (String v : reqHeaders.get(key)) { out.println("\t" + v); } } InputStream in = http.getRequestBody(); if (in != null) { out.println(); IOUtils.copyTo(new InputStreamReader(in), out); in.close(); } out.flush(); out.close(); }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
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: @Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtil.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, null, compareResponse.getControls()); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public Document getDocument(String urlString) { Document doc = null; URLConnection conn = null; InputStream in = null; try { SAXBuilder sxbuild = new SAXBuilder(); if (Osmolt.debug) { outputInterface.printDebugMessage("ProcessOSM", "url: " + urlString); in = new FileInputStream(new File(System.getProperty("user.home") + "/data.osm")); outputInterface.processSetStatus("getting data from " + System.getProperty("user.home") + "/data.osm"); } else { URL url = new URL(urlString); outputInterface.printDebugMessage("ProcessOSM", "url: " + urlString); outputInterface.processSetStatus("connecting Server"); conn = url.openConnection(); outputInterface.processSetStatus("loading Data"); in = conn.getInputStream(); } doc = sxbuild.build(in); } catch (java.net.UnknownHostException e) { outputInterface.printError("Unknown Host: " + urlString); } catch (java.net.SocketTimeoutException e) { outputInterface.printError("Timeout: Server does not response"); } catch (java.net.ConnectException e) { outputInterface.printError("Error Server response: " + e.getMessage()); } catch (java.net.SocketException e) { outputInterface.printError("Error Server response: " + e.getMessage()); } catch (JDOMException e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } catch (IOException e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } catch (Exception e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ioe) { } } return doc; }
11
Code Sample 1: public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } Code Sample 2: public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: private static void copy(File source, File target) throws IOException { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(source)); os = new BufferedOutputStream(new FileOutputStream(target)); int b; while ((b = is.read()) > -1) os.write(b); } finally { try { if (is != null) is.close(); } catch (IOException ignore) { } try { if (os != null) os.close(); } catch (IOException ignore) { } } }
00
Code Sample 1: @Test public void testImageshackUpload() throws Exception { request.setUrl("http://www.imageshack.us/index.php"); request.addParameter("xml", "yes"); request.setFile("fileupload", file); HttpResponse response = httpClient.execute(request); assertTrue(response.is2xxSuccess()); assertTrue(response.getResponseHeaders().size() > 0); String body = IOUtils.toString(response.getResponseBody()); assertTrue(body.contains("<image_link>")); assertTrue(body.contains("<thumb_link>")); assertTrue(body.contains("<image_location>")); assertTrue(body.contains("<image_name>")); response.close(); } Code Sample 2: public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
00
Code Sample 1: public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); } Code Sample 2: private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); }
00
Code Sample 1: private void initialize() { if (!initialized) { if (context.getJavadocLinks() != null) { for (String url : context.getJavadocLinks()) { if (!url.endsWith("/")) { url += "/"; } StringWriter writer = new StringWriter(); try { IOUtils.copy(new URL(url + "package-list").openStream(), writer); } catch (Exception e) { e.printStackTrace(); continue; } StringTokenizer tokenizer2 = new StringTokenizer(writer.toString()); while (tokenizer2.hasMoreTokens()) { javadocByPackage.put(tokenizer2.nextToken(), url); } } } initialized = true; } } Code Sample 2: @Provides @Singleton Properties provideCfg() { InputStream propStream = null; URL url = Thread.currentThread().getContextClassLoader().getResource(PROPERTY_FILE); Properties cfg = new Properties(); if (url != null) { try { log.info("Loading app config from properties: " + url.toURI()); propStream = url.openStream(); cfg.load(propStream); return cfg; } catch (Exception e) { log.warn(e); } } if (cfg.size() < 1) { log.info(PROPERTY_FILE + " doesnt contain any configuration for application properties."); } return cfg; }
00
Code Sample 1: private static File copyJarToPool(File file) { File outFile = new File(RizzToolConstants.TOOL_POOL_FOLDER.getAbsolutePath() + File.separator + file.getName()); if (file != null && file.exists() && file.canRead()) { try { FileChannel inChan = new FileInputStream(file).getChannel(); FileChannel outChan = new FileOutputStream(outFile).getChannel(); inChan.transferTo(0, inChan.size(), outChan); return outFile; } catch (Exception ex) { RizzToolConstants.DEFAULT_LOGGER.error("Exception while copying jar file to tool pool [inFile=" + file.getAbsolutePath() + "] [outFile=" + outFile.getAbsolutePath() + ": " + ex); } } else { RizzToolConstants.DEFAULT_LOGGER.error("Could not copy jar file. File does not exist or can't read file. [inFile=" + file.getAbsolutePath() + "]"); } return null; } Code Sample 2: public byte[] getByteCode() throws IOException { InputStream in = null; ByteArrayOutputStream buf = new ByteArrayOutputStream(2048); try { in = url.openStream(); int b = in.read(); while (b != -1) { buf.write(b); b = in.read(); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } return buf.toByteArray(); }
00
Code Sample 1: public void greatestIncrease(int maxIterations) { double[] increase = new double[numModels]; int[] id = new int[numModels]; Model md = new Model(); double oldPerf = 1; for (int i = 0; i < numModels; i++) { md.addModel(models[i], false); increase[i] = oldPerf - md.getLoss(); id[i] = i; oldPerf = md.getLoss(); } for (int i = 0; i < numModels; i++) { for (int j = 0; j < numModels - 1 - i; j++) { if (increase[j] < increase[j + 1]) { double increasetemp = increase[j]; int temp = id[j]; increase[j] = increase[j + 1]; id[j] = id[j + 1]; increase[j + 1] = increasetemp; id[j + 1] = temp; } } } for (int i = 0; i < maxIterations; i++) { addToEnsemble(models[id[i]]); if (report) ensemble.report(models[id[i]].getName(), allSets); updateBestModel(); } } Code Sample 2: @Override public String getPath() { InputStream in = null; OutputStream out = null; File file = null; try { file = File.createTempFile("java-storage_" + RandomStringUtils.randomAlphanumeric(32), ".tmp"); file.deleteOnExit(); out = new FileOutputStream(file); in = openStream(); IOUtils.copy(in, out); } catch (IOException e) { throw new RuntimeException(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } if (file != null && file.exists()) { return file.getPath(); } return null; }