label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: private void mergeInDefaultMenuItemActionPerformed(java.awt.event.ActionEvent evt) { try { String surl = AutoplotUtil.getProperty("autoplot.default.bookmarks", "http://www.autoplot.org/data/demos.xml"); URL url = new URL(surl); Document doc = AutoplotUtil.readDoc(url.openStream()); List<Bookmark> importBook = Bookmark.parseBookmarks(doc.getDocumentElement()); List<Bookmark> newList = new ArrayList(model.list.size()); for (int i = 0; i < model.list.size(); i++) { newList.add(i, model.list.get(i).copy()); } model.mergeList(importBook, newList); model.setList(newList); formatToFile(bookmarksFile); } catch (SAXException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } } Code Sample 2: public void run() throws Exception { logger.debug("#run enter"); logger.debug("#run orderId = " + orderId); ResultSet rs = null; PreparedStatement ps = null; try { connection.setAutoCommit(false); ps = connection.prepareStatement(SQL_SELECT_ORDER_LINE); ps.setInt(1, orderId); rs = ps.executeQuery(); DeleteOrderLineAction action = new DeleteOrderLineAction(); while (rs.next()) { Integer lineId = rs.getInt("ID"); Integer itemId = rs.getInt("ITEM_ID"); Integer quantity = rs.getInt("QUANTITY"); action.execute(connection, lineId, itemId, quantity); } rs.close(); ps.close(); ps = connection.prepareStatement(SQL_DELETE_ORDER); ps.setInt(1, orderId); ps.executeUpdate(); ps.close(); logger.info("#run order delete OK"); connection.commit(); } catch (SQLException ex) { logger.error("SQLException", ex); connection.rollback(); throw new Exception("Не удалось удалить заказ. Ошибка : " + ex.getMessage()); } finally { connection.setAutoCommit(true); } logger.debug("#run exit"); }
00
Code Sample 1: public void updatePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
11
Code Sample 1: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); } Code Sample 2: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: 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) { } } } Code Sample 2: public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
11
Code Sample 1: static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } } Code Sample 2: public void run(String srcf, String dst) { final Path srcPath = new Path("./" + srcf); final Path desPath = new Path(dst); try { Path[] srcs = FileUtil.stat2Paths(hdfs.globStatus(srcPath), srcPath); OutputStream out = FileSystem.getLocal(conf).create(desPath); for (int i = 0; i < srcs.length; i++) { System.out.println(srcs[i]); InputStream in = hdfs.open(srcs[i]); IOUtils.copyBytes(in, out, conf, false); in.close(); } out.close(); } catch (IOException ex) { System.err.print(ex.getMessage()); } }
00
Code Sample 1: public static String readFromAddress(String address) throws Exception { StringBuilder sb = new StringBuilder(); URL url = new URL(address); URLConnection con = url.openConnection(); con.connect(); InputStream is = (InputStream) con.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String redak = br.readLine(); if (redak == null) break; sb.append(redak); sb.append(System.getProperty("line.separator")); } br.close(); return sb.toString(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static String getResourceFromURL(URL url, String acceptHeader) throws java.io.IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Accept", acceptHeader); urlConnection.setInstanceFollowRedirects(true); BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String content = ""; String line; while ((line = input.readLine()) != null) { content += line; } input.close(); return content; } Code Sample 2: private static void executeDBPatchFile() throws Exception { Connection con = null; PreparedStatement pre_stmt = null; ResultSet rs = null; try { InputStream is = null; URL url = new URL("http://www.hdd-player.de/umc/UMC-DB-Update-Script.sql"); is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:database/umc.db", "", ""); double dbVersion = -1; pre_stmt = con.prepareStatement("SELECT * FROM DB_VERSION WHERE ID_MODUL = 0"); rs = pre_stmt.executeQuery(); if (rs.next()) { dbVersion = rs.getDouble("VERSION"); } String line = ""; con.setAutoCommit(false); boolean collectSQL = false; ArrayList<String> sqls = new ArrayList<String>(); double patchVersion = 0; while ((line = br.readLine()) != null) { if (line.startsWith("[")) { Pattern p = Pattern.compile("\\[.*\\]"); Matcher m = p.matcher(line); m.find(); String value = m.group(); value = value.substring(1, value.length() - 1); patchVersion = Double.parseDouble(value); } if (patchVersion == dbVersion + 1) collectSQL = true; if (collectSQL) { if (!line.equals("") && !line.startsWith("[") && !line.startsWith("--") && !line.contains("--")) { if (line.endsWith(";")) line = line.substring(0, line.length() - 1); sqls.add(line); } } } if (pre_stmt != null) pre_stmt.close(); if (rs != null) rs.close(); for (String sql : sqls) { log.debug("Führe SQL aus Patch Datei aus: " + sql); pre_stmt = con.prepareStatement(sql); pre_stmt.execute(); } if (patchVersion > 0) { log.debug("aktualisiere Versionsnummer in DB"); if (pre_stmt != null) pre_stmt.close(); if (rs != null) rs.close(); pre_stmt = con.prepareStatement("UPDATE DB_VERSION SET VERSION = ? WHERE ID_MODUL = 0"); pre_stmt.setDouble(1, patchVersion); pre_stmt.execute(); } con.commit(); } catch (MalformedURLException exc) { log.error(exc.toString()); throw new Exception("SQL Patch Datei konnte nicht online gefunden werden", exc); } catch (IOException exc) { log.error(exc.toString()); throw new Exception("SQL Patch Datei konnte nicht gelesen werden", exc); } catch (Throwable exc) { log.error("Fehler bei Ausführung der SQL Patch Datei", exc); try { con.rollback(); } catch (SQLException exc1) { } throw new Exception("SQL Patch Datei konnte nicht ausgeführt werden", exc); } finally { try { if (pre_stmt != null) pre_stmt.close(); if (con != null) con.close(); } catch (SQLException exc2) { log.error("Fehler bei Ausführung von SQL Patch Datei", exc2); } } }
00
Code Sample 1: public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } } Code Sample 2: public static String digest(String text, String algorithm, String charsetName) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes(charsetName), 0, text.length()); return convertToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("unexpected exception: " + e, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception: " + e, e); } }
00
Code Sample 1: public static String generateDigest(String message, String DigestAlgorithm) { try { MessageDigest md = MessageDigest.getInstance(DigestAlgorithm); md.update(message.getBytes(), 0, message.length()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException nsae) { return null; } } Code Sample 2: @Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } return status > 199 && status < 400; }
00
Code Sample 1: @Transient private String md5sum(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(text.getBytes()); byte messageDigest[] = md.digest(); return bufferToHex(messageDigest, 0, messageDigest.length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
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.show(); 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.show(); 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.show(); } { 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.show(); 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.show(); } { 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: private void loadMap() { final String wordList = "vietwordlist.txt"; try { File dataFile = new File(supportDir, wordList); if (!dataFile.exists()) { final ReadableByteChannel input = Channels.newChannel(ClassLoader.getSystemResourceAsStream("dict/" + dataFile.getName())); final FileChannel output = new FileOutputStream(dataFile).getChannel(); output.transferFrom(input, 0, 1000000L); input.close(); output.close(); } long fileLastModified = dataFile.lastModified(); if (map == null) { map = new HashMap(); } else { if (fileLastModified <= mapLastModified) { return; } map.clear(); } mapLastModified = fileLastModified; BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8")); String accented; while ((accented = bs.readLine()) != null) { String plain = VietUtilities.stripDiacritics(accented); map.put(plain.toLowerCase(), accented); } bs.close(); } catch (IOException e) { map = null; e.printStackTrace(); JOptionPane.showMessageDialog(this, myResources.getString("Cannot_find_\"") + wordList + myResources.getString("\"_in\n") + supportDir.toString(), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: public static File getClassLoaderFile(String filename) throws IOException { Resource resource = new ClassPathResource(filename); try { return resource.getFile(); } catch (IOException e) { } InputStream is = null; FileOutputStream os = null; try { String tempFilename = RandomStringUtils.randomAlphanumeric(20); File file = File.createTempFile(tempFilename, null); is = resource.getInputStream(); os = new FileOutputStream(file); IOUtils.copy(is, os); return file; } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } Code Sample 2: private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
00
Code Sample 1: public int addRecipe(Recipe recipe) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; ResultSet rs = null; int retVal = -1; try { conn = getConnection(); pst1 = conn.prepareStatement("INSERT INTO recipes (name, instructions, category_id) VALUES (?, ?, ?)"); pst1.setString(1, recipe.getName()); pst1.setString(2, recipe.getInstructions()); pst1.setInt(3, recipe.getCategoryId()); if (pst1.executeUpdate() > 0) { pst2 = conn.prepareStatement("SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? AND category_id = ?"); pst2.setString(1, recipe.getName()); pst2.setString(2, recipe.getInstructions()); pst2.setInt(3, recipe.getCategoryId()); rs = pst2.executeQuery(); conn.commit(); if (rs.next()) { int id = rs.getInt(1); addIngredients(recipe, id); MainFrame.recipePanel.update(); retVal = id; } else { retVal = -1; } } else { retVal = -1; } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add recipe, the exception was " + e.getMessage()); } finally { try { if (rs != null) rs.close(); rs = null; if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (SQLException sqle) { MainFrame.appendStatusText("Can't close database connection."); } } return retVal; } 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()); } }
00
Code Sample 1: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public void loadFromURLPath(String type, URL urlPath, HashMap parentAttributes) throws IOException { this.urlPath = urlPath; this.type = type; JmeBinaryReader jbr = new JmeBinaryReader(); setProperties(jbr, parentAttributes); InputStream loaderInput = urlPath.openStream(); if (type.equals("xml")) { XMLtoBinary xtb = new XMLtoBinary(); ByteArrayOutputStream BO = new ByteArrayOutputStream(); xtb.sendXMLtoBinary(loaderInput, BO); loaderInput = new ByteArrayInputStream(BO.toByteArray()); } else if (!type.equals("binary")) throw new IOException("Unknown LoaderNode flag: " + type); jbr.loadBinaryFormat(this, loaderInput); }
00
Code Sample 1: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } Code Sample 2: public void execute(File sourceFile, File destinationFile, Properties htmlCleanerConfig) { FileReader reader = null; Writer writer = null; try { reader = new FileReader(sourceFile); logger.info("Using source file: " + trimPath(userDir, sourceFile)); if (!destinationFile.getParentFile().exists()) { createDirectory(destinationFile.getParentFile()); } writer = new FileWriter(destinationFile); logger.info("Destination file: " + trimPath(userDir, destinationFile)); execute(reader, writer, htmlCleanerConfig); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); writer = null; } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } }
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 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 String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException, XMLStreamException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); byte[] byteArray = baos.toByteArray(); String resMessage = new String(byteArray, "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + resMessage); return resMessage; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } }
11
Code Sample 1: public static int UsePassword(String username, String password, String new_password) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=ChangePassword&username=" + username + "&password=" + password + "&new_password=" + new_password); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return -1; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return -1; } return 0; } catch (Exception e) { e.printStackTrace(); } return -1; } Code Sample 2: private void loadObject(URL url) throws IOException { InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); int linecounter = 0; try { String line; boolean firstpass = true; String[] coordstext; Material material = null; while (((line = br.readLine()) != null)) { linecounter++; line = line.trim(); if (line.length() > 0) { if (line.startsWith("mtllib")) { String mtlfile = line.substring(6).trim(); loadMtlFile(new URL(url, mtlfile)); } else if (line.startsWith("usemtl")) { String mtlname = line.substring(6).trim(); material = (Material) materials.get(mtlname); } else if (line.charAt(0) == 'v' && line.charAt(1) == ' ') { float[] coords = new float[4]; coordstext = line.split("\\s+"); for (int i = 1; i < coordstext.length; i++) { coords[i - 1] = Float.valueOf(coordstext[i]).floatValue(); } if (firstpass) { rightpoint = coords[0]; leftpoint = coords[0]; toppoint = coords[1]; bottompoint = coords[1]; nearpoint = coords[2]; farpoint = coords[2]; firstpass = false; } if (coords[0] > rightpoint) { rightpoint = coords[0]; } if (coords[0] < leftpoint) { leftpoint = coords[0]; } if (coords[1] > toppoint) { toppoint = coords[1]; } if (coords[1] < bottompoint) { bottompoint = coords[1]; } if (coords[2] > nearpoint) { nearpoint = coords[2]; } if (coords[2] < farpoint) { farpoint = coords[2]; } vertexsets.add(coords); } else if (line.charAt(0) == 'v' && line.charAt(1) == 't') { float[] coords = new float[4]; coordstext = line.split("\\s+"); for (int i = 1; i < coordstext.length; i++) { coords[i - 1] = Float.valueOf(coordstext[i]).floatValue(); } vertexsetstexs.add(coords); } else if (line.charAt(0) == 'v' && line.charAt(1) == 'n') { float[] coords = new float[4]; coordstext = line.split("\\s+"); for (int i = 1; i < coordstext.length; i++) { coords[i - 1] = Float.valueOf(coordstext[i]).floatValue(); } vertexsetsnorms.add(coords); } else if (line.charAt(0) == 'f' && line.charAt(1) == ' ') { coordstext = line.split("\\s+"); int[] v = new int[coordstext.length - 1]; int[] vt = new int[coordstext.length - 1]; int[] vn = new int[coordstext.length - 1]; for (int i = 1; i < coordstext.length; i++) { String fixstring = coordstext[i].replaceAll("//", "/0/"); String[] tempstring = fixstring.split("/"); v[i - 1] = Integer.valueOf(tempstring[0]).intValue(); if (tempstring.length > 1) { vt[i - 1] = Integer.valueOf(tempstring[1]).intValue(); } else { vt[i - 1] = 0; } if (tempstring.length > 2) { vn[i - 1] = Integer.valueOf(tempstring[2]).intValue(); } else { vn[i - 1] = 0; } } Face face = new Face(v, vt, vn, material); faces.add(face); } } } } catch (IOException e) { System.out.println("Failed to read file: " + br.toString()); } catch (NumberFormatException e) { System.out.println("Malformed OBJ (on line " + linecounter + "): " + br.toString() + "\r \r" + e.getMessage()); } }
11
Code Sample 1: public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); } Code Sample 2: public static String getMdPsw(String passwd) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(passwd.getBytes("iso-8859-1"), 0, passwd.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public void viewFile(int file_nx) { FTPClient ftp = new FTPClient(); boolean error = false; try { int reply; ftp.connect("tgftp.nws.noaa.gov"); ftp.login("anonymous", ""); Log.d("WXDroid", "Connected to tgftp.nws.noaa.gov."); Log.d("WXDroid", ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ftp.changeWorkingDirectory("fax"); Log.d("WXDroid", "working directory: " + ftp.printWorkingDirectory()); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); InputStream img_file = ftp.retrieveFileStream("PYAA10.gif"); Intent intent = new Intent(); intent.setClass(WXdroid.this, showProgressFTP.class); startActivity(intent); String storage_state = Environment.getExternalStorageState(); if (storage_state.contains("mounted")) { String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/NOAAWX/"; File imageDirectory = new File(filepath); File local_file = new File(filepath + "PYAA10.gif"); OutputStream out = new FileOutputStream(local_file); byte[] buffer = new byte[1024]; int count; while ((count = img_file.read(buffer)) != -1) { if (Thread.interrupted() == true) { String functionName = Thread.currentThread().getStackTrace()[2].getMethodName() + "()"; throw new InterruptedException("The function " + functionName + " was interrupted."); } out.write(buffer, 0, count); } showImage(); out.flush(); out.close(); img_file.close(); Log.d("WXDroid", "file saved: " + filepath + " " + local_file); } else { Log.d("WXDroid", "The SD card is not mounted"); } ftp.logout(); ftp.disconnect(); } catch (IOException e) { error = true; e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } } Code Sample 2: public static String hash(String plainTextPwd) { MessageDigest hashAlgo; try { hashAlgo = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new QwickException(e); } hashAlgo.update(plainTextPwd.getBytes()); return new String(hashAlgo.digest()); }
11
Code Sample 1: public void addRegisterInfo(HttpServletRequest request) throws ApplicationException { String[] pids = request.getParameterValues("pid"); if (pids == null || pids.length <= 0) throw new ApplicationException("��ѡ��Ҫ���IJ�Ʒ"); RegisterDao registerDao = new RegisterDao(); Register register = registerDao.findPojoById(StrFun.getString(request, "rid"), Register.class); if (register.audit) throw new ApplicationException("��������Ѿ���ˣ��������µ���Ʒ"); DBConnect dbc = null; Connection conn = null; try { dbc = DBConnect.createDBConnect(); conn = dbc.getConnection(); conn.setAutoCommit(false); for (String pid : pids) { RegisterInfo pd = new RegisterInfo(); pd.rid = StrFun.getInt(request, "rid"); pd.pid = Integer.parseInt(pid); pd.productName = StrFun.getString(request, "productName_" + pid); pd.regAmount = StrFun.getInt(request, "regAmount_" + pid); pd.regPrice = StrFun.getInt(request, "regPrice_" + pid); pd.regSalePrice = StrFun.getInt(request, "regSalePrice_" + pid); pd.userNo = ServerUtil.getUserFromSession(request).userNo; if (pd.regAmount <= 0) throw new ApplicationException("�����������Ϊ��"); String sql = "insert into SS_RegisterInfo " + "(pid, rid, productName, regAmount, regPrice, regSalePrice, userNo) " + "values(" + "'" + pd.pid + "', " + "'" + pd.rid + "', " + "'" + pd.productName + "', " + "'" + pd.regAmount + "', " + "'" + pd.regPrice + "', " + "'" + pd.regSalePrice + "', " + "'" + pd.userNo + "' " + ")"; conn.createStatement().executeUpdate(sql); } conn.commit(); } catch (Exception e) { e.printStackTrace(); if (conn != null) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } throw new ApplicationException(e.getMessage(), e); } finally { if (dbc != null) try { dbc.close(); } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: 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 { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: private String executeHttpPreload(HttpResponse response, String xml) throws Exception { GadgetSpec spec = new GadgetSpec(GADGET_URL, xml); RecordingRequestPipeline pipeline = new RecordingRequestPipeline(response); PipelinedDataPreloader preloader = new PipelinedDataPreloader(pipeline, containerConfig); view = "profile"; Gadget gadget = new Gadget().setContext(context).setSpec(spec).setCurrentView(spec.getView("profile")); PipelinedData.Batch batch = getBatch(gadget); Collection<Callable<PreloadedData>> tasks = preloader.createPreloadTasks(context, batch); assertEquals(1, tasks.size()); assertEquals(0, pipeline.requests.size()); Collection<Object> result = tasks.iterator().next().call().toJson(); assertEquals(1, result.size()); assertEquals(1, pipeline.requests.size()); HttpRequest request = pipeline.requests.get(0); assertEquals(HTTP_REQUEST_URL, request.getUri().toString()); assertEquals("POST", request.getMethod()); assertEquals(60, request.getCacheTtl()); return result.iterator().next().toString(); }
00
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static String encryptPassword(String password) { String hash = null; try { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = Base64.encode(raw, false); } catch (Exception e) { } return hash; }
00
Code Sample 1: public static String getInstanceUserdata() throws IOException { int retries = 0; while (true) { try { URL url = new URL("http://169.254.169.254/latest/user-data/"); InputStreamReader rdr = new InputStreamReader(url.openStream()); StringWriter wtr = new StringWriter(); char[] buf = new char[1024]; int bytes; while ((bytes = rdr.read(buf)) > -1) { if (bytes > 0) { wtr.write(buf, 0, bytes); } } rdr.close(); return wtr.toString(); } catch (IOException ex) { if (retries == 5) { logger.debug("Problem getting user data, retries exhausted..."); return null; } else { logger.debug("Problem getting user data, retrying..."); try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException e) { } retries++; } } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("GET REQUEST OR RESPONSE - Send content: " + file.getAbsolutePath()); FileInputStream in = null; try { in = new FileInputStream(file); int bytes = IOUtils.copy(in, out); LOGGER.debug("wrote bytes: " + bytes); out.flush(); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: @Override public LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; }
00
Code Sample 1: protected static String readUrl(URL url) throws IOException { BufferedReader in = null; StringBuffer buf = new StringBuffer(); try { in = new BufferedReader(new InputStreamReader(url.openStream())); final char[] charBuf = new char[1024]; int len = 0; while ((len = in.read(charBuf)) != -1) buf.append(charBuf, 0, len); } finally { if (in != null) in.close(); } return buf.toString(); } Code Sample 2: private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
00
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + StringUtils.byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: String fetch_m3u(String m3u) { InputStream pstream = null; if (m3u.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; return line; } return null; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } Code Sample 2: private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); IOUtils.copy(vds.getContentStream(), m_zout); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void 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 unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: @Override public void run() { URL url = null; FileOutputStream fos = null; FTPClient ftp = null; try { url = new URL(super.getAddress()); String host = url.getHost(); String folder = StringUtils.substringBeforeLast(url.getPath(), "/"); String fileName = StringUtils.substringAfterLast(url.getPath(), "/"); ftp = new FTPClient(host, 21); if (!ftp.connected()) { ftp.connect(); } ftp.login("anonymous", "[email protected]"); logger.info("Connected to " + host + "."); logger.info(ftp.getLastValidReply().getReplyText()); logger.debug("changing dir to " + folder); ftp.chdir(folder); fos = new FileOutputStream(localFileName); logger.info("Downloading file " + fileName + "..."); ftp.setType(FTPTransferType.BINARY); ftp.get(fos, fileName); logger.info("Done."); } catch (Exception e) { logger.error(e.getMessage()); logger.debug(e.getStackTrace()); } finally { try { ftp.quit(); fos.close(); } catch (Exception e) { } } } Code Sample 2: public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
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' " + "AND x.zulfilepath not in (?, ?, ?) " + "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()); pstmt.setString(2, ACTIVITIES_PATH); pstmt.setString(3, FAVOURITES_PATH); pstmt.setString(4, VIEWS_PATH); 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: ServerInfo getServerInfo(String key, String protocol) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IOException, ClassNotFoundException, IllegalBlockSizeException, BadPaddingException { DESedeKeySpec ks = new DESedeKeySpec(Base64.decode(key)); SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede"); SecretKey sk = skf.generateSecret(ks); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, sk); ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource(protocol + ".sobj"); JarURLConnection jc = (JarURLConnection) url.openConnection(); ObjectInputStream os = new ObjectInputStream(jc.getInputStream()); SealedObject so = (SealedObject) os.readObject(); return (ServerInfo) so.getObject(cipher); }
00
Code Sample 1: @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnClear) { passwordField.setText(""); } for (int i = 0; i < 10; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; sql = "select password from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } setVisible(false); setTries(0); Error.log(4003, "Senha de uso �nico verificada positivamente."); Error.log(4002, "Autentica��o etapa 3 encerrada."); ManagerWindow mw = new ManagerWindow(login); mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); int tries = getTries(); if (tries == 0) { Error.log(4004, "Primeiro erro da senha de uso �nico contabilizado."); } else if (tries == 1) { Error.log(4005, "Segundo erro da senha de uso �nico contabilizado."); } else if (tries == 2) { Error.log(4006, "Terceiro erro da senha de uso �nico contabilizado."); Error.log(4007, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 3."); Error.log(4002, "Autentica��o etapa 3 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } } Code Sample 2: public LinkedList<NameValuePair> getScoreboard() { InputStream is = null; String result = ""; LinkedList<NameValuePair> scores = new LinkedList<NameValuePair>(); 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 null; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json = new JSONObject(result); JSONArray data = json.getJSONArray("data"); JSONArray me = json.getJSONArray("me"); for (int i = 0; i < data.length(); i++) { JSONObject single = data.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } for (int i = 0; i < me.length(); i++) { JSONObject single = me.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } System.out.println(json); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return scores; }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void convertToOnline(final String filePath, final DocuBean docuBean) throws Exception { File source = new File(filePath + File.separator + docuBean.getFileName()); File dir = new File(filePath + File.separator + docuBean.getId()); if (!dir.exists()) { dir.mkdir(); } File in = source; boolean isSpace = false; if (source.getName().indexOf(" ") != -1) { in = new File(StringUtils.replace(source.getName(), " ", "")); try { IOUtils.copyFile(source, in); } catch (IOException e) { e.printStackTrace(); } isSpace = true; } File finalPdf = null; try { String outPath = dir.getAbsolutePath(); final File pdf = DocViewerConverter.toPDF(in, outPath); convertToSwf(pdf, outPath, docuBean); finalPdf = new File(outPath + File.separator + FileUtils.getFilePrefix(StringUtils.replace(source.getName(), " ", "")) + "_decrypted.pdf"); if (!finalPdf.exists()) { finalPdf = pdf; } pdfByFirstPageToJpeg(finalPdf, outPath, docuBean); if (docuBean.getSuccess() == 2 && dir.listFiles().length < 2) { docuBean.setSuccess(3); } } catch (Exception e) { throw e; } finally { if (isSpace) { IOUtils.delete(in); } } }
00
Code Sample 1: public static void testString(String string, String expected) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(string.getBytes(), 0, string.length()); String result = toString(md.digest()); System.out.println(expected); System.out.println(result); if (!expected.equals(result)) System.out.println("NOT EQUAL!"); } catch (Exception x) { x.printStackTrace(); } } Code Sample 2: public static int[] sortDescending(int input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] < input[j + 1]) { int mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } }
00
Code Sample 1: private void getViolationsReportBySLATIdYearMonth() throws IOException { String xmlFile10Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportBySLATIdYearMonth.xml"; URL url10; url10 = new URL(bmReportingWSUrl); URLConnection connection10 = url10.openConnection(); HttpURLConnection httpConn10 = (HttpURLConnection) connection10; FileInputStream fin10 = new FileInputStream(xmlFile10Send); ByteArrayOutputStream bout10 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin10, bout10); fin10.close(); byte[] b10 = bout10.toByteArray(); httpConn10.setRequestProperty("Content-Length", String.valueOf(b10.length)); httpConn10.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn10.setRequestProperty("SOAPAction", soapAction); httpConn10.setRequestMethod("POST"); httpConn10.setDoOutput(true); httpConn10.setDoInput(true); OutputStream out10 = httpConn10.getOutputStream(); out10.write(b10); out10.close(); InputStreamReader isr10 = new InputStreamReader(httpConn10.getInputStream()); BufferedReader in10 = new BufferedReader(isr10); String inputLine10; StringBuffer response10 = new StringBuffer(); while ((inputLine10 = in10.readLine()) != null) { response10.append(inputLine10); } in10.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: getViolationsReportBySLATIdYearMonth\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response10.toString()); } 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: private String doSearch(String query) { StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("http://boss.yahooapis.com/ysearch/web/v1/").append(query).append("?appid=wGsFV_DV34EwXnC.2Bt_Ql8Kcir_HmrxMzWUF2fv64CA8ha7e4zgudqXFA8K_J4-&format=xml&filter=-porn"); try { URL url = new URL(queryBuilder.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); return safeParseXml(buffer.toString()); } catch (MalformedURLException e) { log.error("The used url is not right : " + queryBuilder.toString(), e); return "The used url is not right."; } catch (IOException e) { log.error("Problem obtaining search results, connection maybe?", e); return "Problem obtaining search results, connection maybe?"; } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { LOG.debug("copying file"); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tTempFileName)); Datastream tDatastream = new LocalDatastream(this.getGenericFileName(pDeposit), this.getContentType(), tTempFileName); List<Datastream> tDatastreams = new ArrayList<Datastream>(); tDatastreams.add(tDatastream); return tDatastreams; } Code Sample 2: public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { PrintUtil.prt((char) buff.get()); } }
11
Code Sample 1: private void loadNumberFormats() { String fileToLocate = "/" + FILENAME_NUMBER_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new DecimalFormat(parts[1])); } } Code Sample 2: private String fetch(String urlstring) { String content = ""; try { URL url = new URL(urlstring); InputStream is = url.openStream(); BufferedReader d = new BufferedReader(new InputStreamReader(is)); String s; while (null != (s = d.readLine())) { content = content + s + "\n"; } is.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return content; }
11
Code Sample 1: public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException { String id = CryptSHA1.genPhotoID(userLogin, title); String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf(".")); String destination = basePathImage + id + extension; FileInputStream fis = new FileInputStream(pathToPhoto); FileOutputStream fos = new FileOutputStream(destination); FileChannel fci = fis.getChannel(); FileChannel fco = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int read = fci.read(buffer); if (read == -1) break; buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); fco.close(); fos.close(); fis.close(); ImageIcon image; ImageIcon thumb; String destinationThumb = basePathImage + "thumb/" + id + extension; image = new ImageIcon(destination); int maxSize = 150; int origWidth = image.getIconWidth(); int origHeight = image.getIconHeight(); if (origWidth > origHeight) { thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH)); } else { thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH)); } BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(thumb.getImage(), 0, 0, null); try { ImageIO.write(bi, "JPG", new File(destinationThumb)); } catch (IOException ioe) { System.out.println("Error occured saving thumbnail"); } Photo photo = new Photo(id); photo.setTitle(title); photo.basePathImage = basePathImage; return photo; } Code Sample 2: public void encryptFile(String originalFile, String encryptedFile, String password) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(originalFile); out = new CipherOutputStream(new FileOutputStream(encryptedFile), cipher); 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: @Override public int write(FileStatus.FileTrackingStatus fileStatus, InputStream input, PostWriteAction postWriteAction) throws WriterException, InterruptedException { String key = logFileNameExtractor.getFileName(fileStatus); int wasWritten = 0; FileOutputStreamPool fileOutputStreamPool = fileOutputStreamPoolFactory.getPoolForKey(key); RollBackOutputStream outputStream = null; File file = null; try { file = getOutputFile(key); lastWrittenFile = file; outputStream = fileOutputStreamPool.open(key, compressionCodec, file, true); outputStream.mark(); wasWritten = IOUtils.copy(input, outputStream); if (postWriteAction != null) { postWriteAction.run(wasWritten); } } catch (Throwable t) { LOG.error(t.toString(), t); if (outputStream != null && wasWritten > 0) { LOG.error("Rolling back file " + file.getAbsolutePath()); try { outputStream.rollback(); } catch (IOException e) { throwException(e); } catch (InterruptedException e) { throw e; } } throwException(t); } finally { try { fileOutputStreamPool.releaseFile(key); } catch (IOException e) { throwException(e); } } return wasWritten; } Code Sample 2: public static void decompress(File apps,File f) throws IOException{ String filename=f.getName(); filename=filename.substring(0,filename.length()-PACK_FILE_SUFFIX.length()); File dir=new File(apps,filename); if(!dir.exists()){ dir.mkdirs(); } if(dir.isDirectory()){ JarFile jar=new JarFile(f); Enumeration<JarEntry> files=jar.entries(); while(files.hasMoreElements()){ JarEntry je=files.nextElement(); if(je.isDirectory()){ File item=new File(dir,je.getName()); item.mkdirs(); }else{ File item=new File(dir,je.getName()); item.getParentFile().mkdirs(); InputStream input=jar.getInputStream(je); FileOutputStream out=new FileOutputStream(item); IOUtils.copy(input, out); input.close(); out.close(); } //System.out.println(je.isDirectory() + je.getName()); } } }
00
Code Sample 1: public String doAction(Action commandAction) throws Exception { Map<String, String> args = commandAction.getArgs(); EnumCommandActionType actionType = commandAction.getType(); String actionResult = ""; switch(actionType) { case SEND: String method = getMethod(); String contentType = getContentType(); String url = "http://" + getHost() + ":" + getPort() + "/"; String pathUrl = ""; String data = ""; if (args.containsKey("method")) { method = args.get("method").toUpperCase(); } else if (args.containsKey("contenttype")) { contentType = args.get("contenttype").toLowerCase(); } else if (args.containsKey("postdata")) { contentType = args.get("postdata").toLowerCase(); } if (!allowedHttpMethods.contains(method.toUpperCase())) { throw new GatewayException("Invalid HTTP method specified for command Action."); } String commandStr = Pattern.compile("^/").matcher(args.get("command")).replaceAll(""); if ("GET".equals(method)) { pathUrl = commandStr; } else { String[] argStr = args.get("command").split("\\?"); pathUrl = argStr[0]; data = argStr[1]; } url += pathUrl; URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setUseCaches(false); conn.setRequestMethod(method); conn.setConnectTimeout(getConnectTimeout()); if ("POST".equals(method)) { conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Content-Length", Integer.toString(data.length())); OutputStream outputStream = conn.getOutputStream(); outputStream.write(data.getBytes()); outputStream.flush(); } InputStream inputStream = conn.getInputStream(); if (conn.getResponseCode() != 200) { Integer responseCode = conn.getResponseCode(); conn.disconnect(); throw new GatewayException("Invalid response from server, expecting status code 200 but received " + responseCode.toString()); } Calendar endTime = Calendar.getInstance(); endTime.add(Calendar.MILLISECOND, getReadTimeout()); while (Calendar.getInstance().before(endTime) && inputStream.available() == 0) { try { Thread.sleep(50); } catch (Exception e) { } } while (inputStream.available() > 0) { actionResult += (char) inputStream.read(); } if (actionResult.length() > 0) { responseBuffer = actionResult; actionResult = ""; break; } conn.disconnect(); break; case READ: actionResult = responseBuffer; responseBuffer = ""; break; } return actionResult; } Code Sample 2: @Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (beforeServingFile(req, resp)) { String pathInfo = req.getPathInfo(); Validate.notNull(pathInfo, "the path info is null -> the sevlet should be mapped with /<mapping>/*"); String resurouce = pathInfo.substring(1); if (log.isDebugEnabled()) { log.debug("resource to expose: " + resurouce); } String extension = resurouce.substring(resurouce.lastIndexOf('.') + 1); MimeType mimeType = MimeTypeRegistry.getByExtension(extension); Validate.notNull(mimeType, "no mimetype found for extension: " + extension); if (log.isDebugEnabled()) { log.debug("the mime type to set: " + mimeType.getMimeType()); } File f = new File(mappedFolder, resurouce); Validate.isTrue(f.exists(), "file: " + f + " does not exist"); Validate.isTrue(f.canRead(), "can not read the file: " + f); if (log.isDebugEnabled()) { log.debug("exposing the file: " + f); } resp.setContentType(mimeType.getMimeType()); FileInputStream fis = new FileInputStream(f); ServletOutputStream os = resp.getOutputStream(); IOUtils.copy(fis, os); os.flush(); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(os); } }
00
Code Sample 1: public static void copyFile(File oldFile, File newFile) throws Exception { newFile.getParentFile().mkdirs(); newFile.createNewFile(); FileChannel srcChannel = new FileInputStream(oldFile).getChannel(); FileChannel dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public boolean authorize(String username, String password, String filename) { open(filename); boolean isAuthorized = false; StringBuffer encPasswd = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } String encPassword = encPasswd.toString(); String tempPassword = getPassword(username); System.out.println("epass" + encPassword); System.out.println("pass" + tempPassword); if (tempPassword.equals(encPassword)) { isAuthorized = true; } else { isAuthorized = false; } close(); return isAuthorized; }
11
Code Sample 1: @Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
11
Code Sample 1: public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); } Code Sample 2: public EncodedScript(PackageScript source, DpkgData data) throws IOException { _source = source; final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream output = null; try { output = MimeUtility.encode(bytes, BASE64); } catch (final MessagingException e) { throw new IOException("Failed to uuencode script. name=[" + _source.getFriendlyName() + "], reason=[" + e.getMessage() + "]."); } IOUtils.write(HEADER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); IOUtils.copy(_source.getSource(data), output); output.flush(); IOUtils.write(FOOTER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); output.close(); bytes.close(); _encoded = bytes.toString(Dpkg.CHAR_ENCODING); }
00
Code Sample 1: public InputStream getPage(String page) throws IOException { URL url = new URL(hattrickServerURL + "/Common/" + page); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestProperty("Cookie", sessionCookie); return huc.getInputStream(); } Code Sample 2: private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
11
Code Sample 1: public void writeToFile(File out) throws IOException, DocumentException { FileChannel inChannel = new FileInputStream(pdf_file).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 static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
00
Code Sample 1: private static File[] getWsdls(File dirfile) throws Exception { File[] allfiles = dirfile.listFiles(); List<File> files = new ArrayList<File>(); if (allfiles != null) { MessageDigest md = MessageDigest.getInstance("MD5"); String outputDir = argMap.get(OUTPUT_DIR); for (File file : allfiles) { if (file.getName().endsWith(WSDL_SUFFIX)) { files.add(file); } if (file.getName().endsWith(WSDL_SUFFIX) || file.getName().endsWith(XSD_SUFFIX)) { md.update(FileUtil.getBytes(file)); } } computedHash = md.digest(); hashFile = new File(outputDir + File.separator + argMap.get(BASE_PACKAGE).replace('.', File.separatorChar) + File.separator + "hash.md5"); if (hashFile.exists()) { byte[] readHash = FileUtil.getBytes(hashFile); if (Arrays.equals(readHash, computedHash)) { System.out.println("Skipping generation, files not changed."); files.clear(); } } } File[] filesarr = new File[files.size()]; files.toArray(filesarr); return filesarr; } Code Sample 2: public static void copyFile(File in, File out) throws FileNotFoundException, IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { sourceChannel.close(); } catch (Exception ex) { } try { destinationChannel.close(); } catch (Exception ex) { } } }
11
Code Sample 1: public void testQueryForBinary() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + "images/photo.png"); assertNotNull(source); assertEquals(false, source.exists()); OutputStream os = source.getOutputStream(); assertNotNull(os); String content = "foo is a bar"; os.write(content.getBytes()); os.flush(); os.close(); QueryResultSource qResult = (QueryResultSource) resolveSource(BASE_URL + "images?/*[contains(local-name(), 'photo.png')]"); assertNotNull(qResult); Collection results = qResult.getChildren(); assertEquals(1, results.size()); Iterator it = results.iterator(); JCRNodeSource rSrc = (JCRNodeSource) it.next(); InputStream rSrcIn = rSrc.getInputStream(); ByteArrayOutputStream actualOut = new ByteArrayOutputStream(); IOUtils.copy(rSrcIn, actualOut); rSrcIn.close(); assertEquals(content, actualOut.toString()); actualOut.close(); rSrc.delete(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
00
Code Sample 1: private void criarQuestaoMultiplaEscolha(QuestaoMultiplaEscolha q) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO multipla_escolha (id_questao, texto, gabarito) VALUES (?,?,?)"; try { for (Alternativa alternativa : q.getAlternativa()) { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setString(2, alternativa.getTexto()); stmt.setBoolean(3, alternativa.getGabarito()); stmt.executeUpdate(); conexao.commit(); } } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: private int[] Tri(int[] pertinence, int taille) { boolean change = true; int tmp; while (change) { change = false; for (int i = 0; i < taille - 2; i++) { if (pertinence[i] < pertinence[i + 1]) { tmp = pertinence[i]; pertinence[i] = pertinence[i + 1]; pertinence[i + 1] = tmp; change = true; } } } return pertinence; }
00
Code Sample 1: public File getFile(String file) { DirProperties dp; List files = new ArrayList(); for (int i = 0; i < locs.size(); i++) { dp = (DirProperties) locs.get(i); if (dp.isReadable()) { File g = new File(dp.getLocation() + slash() + file); if (g.exists()) files.add(g); } } if (files.size() == 0) { throw new UnsupportedOperationException("at least one DirProperty should get 'read=true'"); } else if (files.size() == 1) { return (File) files.get(0); } else { File fromFile = (File) files.get(files.size() - 2); File toFile = (File) files.get(files.size() - 1); byte reading[] = new byte[2024]; try { FileInputStream stream = new FileInputStream(fromFile); FileOutputStream outStr = new FileOutputStream(toFile); while (stream.read(reading) != -1) { outStr.write(reading); } } catch (FileNotFoundException ex) { getLogger().severe("FileNotFound: while copying from " + fromFile + " to " + toFile); } catch (IOException ex) { getLogger().severe("IOException: while copying from " + fromFile + " to " + toFile); } return toFile; } } Code Sample 2: public static String getMD5(String value) { if (StringUtils.isBlank(value)) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes("UTF-8")); return toHexString(md.digest()); } catch (Throwable e) { return null; } }
11
Code Sample 1: public void create(File target) { if ("dir".equals(type)) { File dir = new File(target, name); dir.mkdirs(); for (Resource c : children) { c.create(dir); } } else if ("package".equals(type)) { String[] dirs = name.split("\\."); File parent = target; for (String d : dirs) { parent = new File(parent, d); } parent.mkdirs(); for (Resource c : children) { c.create(parent); } } else if ("file".equals(type)) { InputStream is = getInputStream(); File file = new File(target, name); try { if (is != null) { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); fos.flush(); fos.close(); } else { PrintStream ps = new PrintStream(file); ps.print(content); ps.flush(); ps.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if ("zip".equals(type)) { try { unzip(target); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException("unknown resource type: " + type); } } Code Sample 2: public void execute() throws MojoExecutionException, MojoFailureException { try { this.getLog().info("copy source web.xml - " + this.getWebXml() + " to build dir (source web.xml required if mergewebxml execution is enabled)"); File destination = new File(this.getBuildDir(), "web.xml"); if (!destination.exists()) { destination.getParentFile().mkdirs(); destination.createNewFile(); } FileIOUtils.copyFile(this.getWebXml(), destination); for (int i = 0; i < this.getCompileTarget().length; i++) { File moduleFile = null; for (Iterator it = this.getProject().getCompileSourceRoots().iterator(); it.hasNext() && moduleFile == null; ) { File check = new File(it.next().toString() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } for (Iterator it = this.getProject().getResources().iterator(); it.hasNext(); ) { Resource r = (Resource) it.next(); File check = new File(r.getDirectory() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } ClassLoader loader = this.fixThreadClasspath(); if (moduleFile == null) { try { String classpath = "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"; InputStream is = loader.getResourceAsStream(classpath); System.out.println("Looking for classpath: " + classpath + "(" + (is != null) + ")"); if (is != null) { File temp = new File(this.getBuildDir(), this.getCompileTarget()[i].concat(".gwt.xml")); FileOutputStream fos = new FileOutputStream(temp); FileIOUtils.copyStream(is, fos); moduleFile = temp; } } catch (IOException e) { this.getLog().info(e); } } GwtWebInfProcessor processor = null; try { if (moduleFile != null) { getLog().info("Module file: " + moduleFile.getAbsolutePath()); processor = new GwtWebInfProcessor(this.getCompileTarget()[i], moduleFile, destination.getAbsolutePath(), destination.getAbsolutePath(), this.isWebXmlServletPathAsIs()); processor.process(); } else { throw new MojoExecutionException("module file null"); } } catch (ExitException e) { this.getLog().info(e.getMessage()); } } } catch (Exception e) { throw new MojoExecutionException("Unable to merge web.xml", e); } }
11
Code Sample 1: private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); } Code Sample 2: public static void unzipModel(String filename, String tempdir) throws Exception { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(filename); int BUFFER = 2048; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(tempdir + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); throw new Exception("Can not expand model in \"" + tempdir + "\" because:\n" + e.getMessage()); } }
11
Code Sample 1: public static void copy(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: private synchronized File gzipTempFile(File tempFile) throws BlogunityException { try { File gzippedFile = new File(BlogunityManager.getSystemConfiguration().getTempDir(), tempFile.getName() + ".gz"); GZIPOutputStream zos = new GZIPOutputStream(new FileOutputStream(gzippedFile)); byte[] readBuffer = new byte[2156]; int bytesIn = 0; FileInputStream fis = new FileInputStream(tempFile); while ((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } fis.close(); zos.close(); return gzippedFile; } catch (Exception e) { throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.FEED_GZIP_FAILED, e)); } }
11
Code Sample 1: private void copyFile(URL from, File to) { try { InputStream is = from.openStream(); IOUtils.copy(is, new FileOutputStream(to)); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void create() throws IOException { FileChannel fc = new FileInputStream(sourceFile).getChannel(); for (RangeArrayElement element : array) { FileChannel fc_ = fc.position(element.starting()); File part = new File(destinationDirectory, "_0x" + Long.toHexString(element.starting()) + ".partial"); FileChannel partfc = new FileOutputStream(part).getChannel(); partfc.transferFrom(fc_, 0, element.getSize()); partfc.force(true); partfc.close(); } fc.close(); }
11
Code Sample 1: private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } Code Sample 2: private void parseTemplate(File templateFile, Map dataMap) throws ContainerException { Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(templateFile)); } catch (FileNotFoundException e) { throw new ContainerException(e); } String targetDirectoryName = args.length > 1 ? args[1] : null; if (targetDirectoryName == null) { targetDirectoryName = target; } String targetDirectory = ofbizHome + targetDirectoryName + args[0]; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { throw new ContainerException("Unable to create target directory - " + targetDirectory); } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } Writer writer = null; try { writer = new FileWriter(targetDirectory + templateFile.getName()); } catch (IOException e) { throw new ContainerException(e); } try { FreeMarkerWorker.renderTemplate(templateFile.getAbsolutePath(), reader, dataMap, writer); } catch (Exception e) { throw new ContainerException(e); } try { writer.flush(); writer.close(); } catch (IOException e) { throw new ContainerException(e); } }
11
Code Sample 1: private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } } Code Sample 2: public void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
00
Code Sample 1: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: public void deploy(String baseDir, boolean clean) throws IOException { try { ftp.connect(hostname, port); log.debug("Connected to: " + hostname + ":" + port); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Error logging onto ftp server. FTPClient returned code: " + reply); } log.debug("Logged in"); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); if (clean) { deleteDir(remoteDir); } storeFolder(baseDir, remoteDir); } finally { ftp.disconnect(); } }
00
Code Sample 1: static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; } Code Sample 2: public void testDelegateUsage() throws IOException { MockControl elementParserControl = MockControl.createControl(ElementParser.class); ElementParser elementParser = (ElementParser) elementParserControl.getMock(); elementParserControl.replay(); URL url = getClass().getResource("/net/sf/ngrease/core/ast/simple-element.ngr"); ElementSource source = new ElementSourceUrlImpl(url, elementParser); elementParserControl.verify(); elementParserControl.reset(); Element element = new ElementDefaultImpl(""); elementParser.parse(url.openStream()); elementParserControl.setMatcher(new ArgumentsMatcher() { public boolean matches(Object[] arg0, Object[] arg1) { if (!arg0[0].getClass().equals(arg1[0].getClass())) { return false; } return true; } public String toString(Object[] arg0) { return Arrays.asList(arg0).toString(); } }); elementParserControl.setReturnValue(element, 1); elementParserControl.replay(); Element elementAgain = source.getElement(); elementParserControl.verify(); assertTrue(element == elementAgain); }
00
Code Sample 1: private static String executeGet(String urlStr) { StringBuffer result = new StringBuffer(); try { Authentication.doIt(); URL url = new URL(urlStr); System.out.println("Host: " + url.getHost()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result.toString(); } Code Sample 2: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
11
Code Sample 1: @Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } } Code Sample 2: public void SplitFile(File in, File out0, File out1, long pos) throws IOException { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out0); FileChannel fic = fis.getChannel(); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, pos); foc.close(); fos = new FileOutputStream(out1); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size() - pos); foc.close(); fic.close(); }
11
Code Sample 1: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
11
Code Sample 1: public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } } Code Sample 2: public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
11
Code Sample 1: public static void main(String[] args) throws IOException { long readfilelen = 0; BufferedRandomAccessFile brafReadFile, brafWriteFile; brafReadFile = new BufferedRandomAccessFile("C:\\WINNT\\Fonts\\STKAITI.TTF"); readfilelen = brafReadFile.initfilelen; brafWriteFile = new BufferedRandomAccessFile(".\\STKAITI.001", "rw", 10); byte buf[] = new byte[1024]; int readcount; long start = System.currentTimeMillis(); while ((readcount = brafReadFile.read(buf)) != -1) { brafWriteFile.write(buf, 0, readcount); } brafWriteFile.close(); brafReadFile.close(); System.out.println("BufferedRandomAccessFile Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); java.io.FileInputStream fdin = new java.io.FileInputStream("C:\\WINNT\\Fonts\\STKAITI.TTF"); java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fdin, 1024); java.io.DataInputStream dis = new java.io.DataInputStream(bis); java.io.FileOutputStream fdout = new java.io.FileOutputStream(".\\STKAITI.002"); java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(fdout, 1024); java.io.DataOutputStream dos = new java.io.DataOutputStream(bos); start = System.currentTimeMillis(); for (int i = 0; i < readfilelen; i++) { dos.write(dis.readByte()); } dos.close(); dis.close(); System.out.println("DataBufferedios Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); } Code Sample 2: private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); }
11
Code Sample 1: public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
11
Code Sample 1: public void saveProjectFile(File aFile) { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); File destDir = new File(theProjectsDirectory, sdf.format(Calendar.getInstance().getTime())); if (destDir.mkdirs()) { File outFile = new File(destDir, "project.xml"); try { FileChannel sourceChannel = new FileInputStream(aFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(outFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException e) { e.printStackTrace(); } finally { aFile.delete(); } } } Code Sample 2: private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); }
00
Code Sample 1: public static void main(String[] args) { if (args.length == 0) { System.out.println("Specify name of the file, just one entry per line"); System.exit(0); } File inFile = new File(args[0]); BufferedReader myBR = null; File outFile = new File(args[0] + ".xml"); BufferedWriter myBW = null; try { myBR = new BufferedReader(new FileReader(inFile)); myBW = new BufferedWriter(new FileWriter(outFile)); } catch (Exception ex) { System.out.println("IN: " + inFile.getAbsolutePath()); System.out.println("OUT: " + outFile.getAbsolutePath()); ex.printStackTrace(); System.exit(0); } try { String readLine; while ((readLine = myBR.readLine()) != null) { myBW.write("<dbColumn name=\"" + readLine + "\" display=\"" + readLine + "\" panel=\"CENTER\" >"); myBW.write("\n"); myBW.write("<dbType name=\"text\" maxVal=\"10\" defaultVal=\"\" sizeX=\"5\"/>"); myBW.write("\n"); myBW.write("</dbColumn>"); myBW.write("\n"); } myBW.close(); myBR.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } System.out.println("OUT: " + outFile.getAbsolutePath()); System.out.println("erzeugt"); } Code Sample 2: public static String sendRequest(String urlstring) { URL url; String line; Log.i("DVBMonitor", "Please wait while receiving data from dvb..."); try { url = new URL(urlstring); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); if ((line = in.readLine()) != null) { return line; } else { return null; } } catch (Exception ex) { Log.e("DVBMonitor", ex.toString() + " while sending request to dvb"); return null; } }
00
Code Sample 1: ServiceDescription getServiceDescription() throws ConfigurationException { final XPath pathsXPath = this.xPathFactory.newXPath(); try { final Node serviceDescriptionNode = (Node) pathsXPath.evaluate(ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration, XPathConstants.NODE); final String title = getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.TITLE_ELEMENT); ServiceDescription.Builder builder = new ServiceDescription.Builder(title, Migrate.class.getCanonicalName()); Property[] serviceProperties = getServiceProperties(serviceDescriptionNode); builder.author(getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.CREATOR_ELEMENT)); builder.classname(this.canonicalServiceName); builder.description(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.DESCRIPTION_ELEMENT)); final String serviceVersion = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.VERSION_ELEMENT); final Tool toolDescription = getToolDescriptionElement(serviceDescriptionNode); String identifier = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.IDENTIFIER_ELEMENT); if (identifier == null || "".equals(identifier)) { try { final MessageDigest identDigest = MessageDigest.getInstance("MD5"); identDigest.update(this.canonicalServiceName.getBytes()); final String versionInfo = (serviceVersion != null) ? serviceVersion : ""; identDigest.update(versionInfo.getBytes()); final URI toolIDURI = toolDescription.getIdentifier(); final String toolIdentifier = toolIDURI == null ? "" : toolIDURI.toString(); identDigest.update(toolIdentifier.getBytes()); final BigInteger md5hash = new BigInteger(identDigest.digest()); identifier = md5hash.toString(16); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } } builder.identifier(identifier); builder.version(serviceVersion); builder.tool(toolDescription); builder.instructions(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.INSTRUCTIONS_ELEMENT)); builder.furtherInfo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.FURTHER_INFO_ELEMENT)); builder.logo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.LOGO_ELEMENT)); builder.serviceProvider(this.serviceProvider); final DBMigrationPathFactory migrationPathFactory = new DBMigrationPathFactory(this.configuration); final MigrationPaths migrationPaths = migrationPathFactory.getAllMigrationPaths(); builder.paths(MigrationPathConverter.toPlanetsPaths(migrationPaths)); builder.inputFormats(migrationPaths.getInputFormatURIs().toArray(new URI[0])); builder.parameters(getUniqueParameters(migrationPaths)); builder.properties(serviceProperties); return builder.build(); } catch (XPathExpressionException xPathExpressionException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), xPathExpressionException); } catch (NullPointerException nullPointerException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), nullPointerException); } } Code Sample 2: public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: public void setPassword(String plaintext) throws java.security.NoSuchAlgorithmException { StringBuffer encrypted = new StringBuffer(); java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(plaintext.getBytes()); byte[] digestArray = digest.digest(); for (int i = 0; i < digestArray.length; i++) { encrypted.append(byte2hex(digestArray[i])); } setEncryptedPassword(encrypted.toString()); } Code Sample 2: public static String login() throws Exception { if (sid == null) { String login = ROLAPClientAux.loadProperties().getProperty("user"); String password = ROLAPClientAux.loadProperties().getProperty("password"); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); String password2 = asHexString(md.digest()); String query = "/server/login?user=" + login + "&extern_password=" + password + "&password=" + password2; Vector<String> res = ROLAPClientAux.sendRequest(query); String vals[] = res.get(0).split(";"); sid = vals[0]; } return sid; }
00
Code Sample 1: public static JSONObject delete(String uid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(DELETE_URI + "?uid=" + uid); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); } Code Sample 2: public void overwriteFileTest() throws Exception { File filefrom = new File("/tmp/from.txt"); File fileto = new File("/tmp/to.txt"); InputStream from = null; OutputStream to = null; try { from = new FileInputStream(filefrom); to = new FileOutputStream(fileto); 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) { from.close(); } if (to != null) { to.close(); } } }
00
Code Sample 1: static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: 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(); } }
00
Code Sample 1: private void add(Hashtable applicantInfo) throws Exception { String mode = "".equals(getParam("applicant_id_gen").trim()) ? "update" : "insert"; String applicant_id = getParam("applicant_id"); String password = getParam("password"); if ("".equals(applicant_id)) applicant_id = getParam("applicant_id_gen"); if ("".equals(getParam("applicant_name"))) throw new Exception("Can not have empty fields!"); applicantInfo.put("id", applicant_id); applicantInfo.put("password", password); applicantInfo.put("name", getParam("applicant_name")); applicantInfo.put("address1", getParam("address1")); applicantInfo.put("address2", getParam("address2")); applicantInfo.put("address3", getParam("address3")); applicantInfo.put("city", getParam("city")); applicantInfo.put("state", getParam("state")); applicantInfo.put("poscode", getParam("poscode")); applicantInfo.put("country_code", getParam("country_list")); applicantInfo.put("email", getParam("email")); applicantInfo.put("phone", getParam("phone")); String birth_year = getParam("birth_year"); String birth_month = getParam("birth_month"); String birth_day = getParam("birth_day"); applicantInfo.put("birth_year", birth_year); applicantInfo.put("birth_month", birth_month); applicantInfo.put("birth_day", birth_day); applicantInfo.put("gender", getParam("gender")); String birth_date = birth_year + "-" + fmt(birth_month) + "-" + fmt(birth_day); applicantInfo.put("birth_date", birth_date); Db db = null; String sql = ""; Connection conn = null; try { db = new Db(); conn = db.getConnection(); conn.setAutoCommit(false); Statement stmt = db.getStatement(); SQLRenderer r = new SQLRenderer(); boolean found = false; { r.add("applicant_id"); r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLSelect("adm_applicant"); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) found = true; else found = false; } if (found && !"update".equals(mode)) throw new Exception("Applicant Id was invalid!"); { r.clear(); r.add("password", (String) applicantInfo.get("password")); r.add("applicant_name", (String) applicantInfo.get("name")); r.add("address1", (String) applicantInfo.get("address1")); r.add("address2", (String) applicantInfo.get("address2")); r.add("address3", (String) applicantInfo.get("address3")); r.add("city", (String) applicantInfo.get("city")); r.add("state", (String) applicantInfo.get("state")); r.add("poscode", (String) applicantInfo.get("poscode")); r.add("country_code", (String) applicantInfo.get("country_code")); r.add("phone", (String) applicantInfo.get("phone")); r.add("birth_date", (String) applicantInfo.get("birth_date")); r.add("gender", (String) applicantInfo.get("gender")); } if (!found) { r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLInsert("adm_applicant"); stmt.executeUpdate(sql); } else { r.update("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLUpdate("adm_applicant"); stmt.executeUpdate(sql); } conn.commit(); } catch (DbException dbex) { throw dbex; } catch (SQLException sqlex) { try { conn.rollback(); } catch (SQLException rollex) { } throw sqlex; } finally { if (db != null) db.close(); } } Code Sample 2: public void fetchKey() throws IOException { String strurl = MessageFormat.format(keyurl, new Object[] { username, secret, login, session }); StringBuffer result = new StringBuffer(); BufferedReader reader = null; URL url = null; try { url = new URL(strurl); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { result.append(line); } } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } Pattern p = Pattern.compile("<key>(.*)</key>"); Matcher m = p.matcher(result.toString()); if (m.matches()) { this.key = m.group(1); } }
11
Code Sample 1: private boolean createPKCReqest(String keystoreLocation, String pw) { boolean created = false; Security.addProvider(new BouncyCastleProvider()); KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when creating PKC request: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when creating PKC request: " + e.getMessage()); } return false; } PKCS10CertificationRequest request = null; PublicKey pk = cert.getPublicKey(); try { request = new PKCS10CertificationRequest("SHA1with" + pk.getAlgorithm(), new X500Principal(((X509Certificate) cert).getSubjectDN().toString()), pk, new DERSet(), (PrivateKey) ks.getKey("saws", pw.toCharArray())); PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(new FileOutputStream("sawsRequest.csr"))); pemWrt.writeObject(request); pemWrt.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error creating PKC request file: " + e.getMessage()); } return false; } return created; } Code Sample 2: String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
00
Code Sample 1: public static final File getFile(final URL url) throws IOException { final File shortcutFile; final File currentFile = files.get(url); if (currentFile == null || !currentFile.exists()) { shortcutFile = File.createTempFile("windowsIsLame", ".vbs"); shortcutFile.deleteOnExit(); files.put(url, shortcutFile); final InputStream stream = url.openStream(); final FileOutputStream out = new FileOutputStream(shortcutFile); try { StreamUtils.copy(stream, out); } finally { out.close(); stream.close(); } } else shortcutFile = currentFile; return shortcutFile; } Code Sample 2: @Override public byte[] read(String path) throws PersistenceException { InputStream reader = null; ByteArrayOutputStream sw = new ByteArrayOutputStream(); try { reader = new FileInputStream(path); IOUtils.copy(reader, sw); } catch (Exception e) { LOGGER.error("fail to read file - " + path, e); throw new PersistenceException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error("fail to close reader", e); } } } return sw.toByteArray(); }
11
Code Sample 1: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } } Code Sample 2: private List<Document> storeDocuments(List<Document> documents) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); List<Document> newDocuments = new ArrayList<Document>(); try { session.beginTransaction(); Preference preference = new PreferenceModel(); preference = (Preference) preference.doList(preference).get(0); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); if (documents != null && !documents.isEmpty()) { for (Iterator<Document> iter = documents.iterator(); iter.hasNext(); ) { Document document = iter.next(); if (AppConstants.STATUS_ACTIVE.equals(document.getStatus())) { try { document = (Document) preAdd(document, getParams()); File fileIn = new File(preference.getScanLocation() + File.separator + document.getName()); File fileOut = new File(preference.getStoreLocation() + File.separator + document.getName()); FileInputStream in = new FileInputStream(fileIn); FileOutputStream out = new FileOutputStream(fileOut); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); document.doAdd(document); boolean isDeleted = fileIn.delete(); System.out.println("Deleted scan folder file: " + document.getName() + ":" + isDeleted); if (isDeleted) { document.setStatus(AppConstants.STATUS_PROCESSING); int uploadCount = 0; if (document.getUploadCount() != null) { uploadCount = document.getUploadCount(); } uploadCount++; document.setUploadCount(uploadCount); newDocuments.add(document); } } catch (Exception add_ex) { add_ex.printStackTrace(); } } else if (AppConstants.STATUS_PROCESSING.equals(document.getStatus())) { int uploadCount = document.getUploadCount(); if (uploadCount < 5) { uploadCount++; document.setUploadCount(uploadCount); System.out.println("increase upload count: " + document.getName() + ":" + uploadCount); newDocuments.add(document); } else { System.out.println("delete from documents list: " + document.getName()); } } else if (AppConstants.STATUS_INACTIVE.equals(document.getStatus())) { document.setFixFlag(AppConstants.FLAG_NO); newDocuments.add(document); } } } } catch (Exception ex) { ex.printStackTrace(); } return newDocuments; }
00
Code Sample 1: public static String base64HashedString(String v) { String base64HashedPassword = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(v.getBytes()); String hashedPassword = new String(md.digest()); sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); base64HashedPassword = enc.encode(hashedPassword.getBytes()); } catch (java.security.NoSuchAlgorithmException e) { throw new NSForwardException(e, "Couldn't find the SHA hash algorithm; perhaps you do not have the SunJCE security provider installed properly?"); } return base64HashedPassword; } Code Sample 2: public Atividade insertAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade (idatividade, requerente_idrequerente, datacriacao, datatermino, valor, tipoatividade, descricao, fase_idfase, estado) " + "values " + "(nextval('seq_atividade'), " + atividade.getRequerente().getIdRequerente() + ", " + "'" + atividade.getDataCriacao() + "', '" + atividade.getDataTermino() + "', '" + atividade.getValor() + "', '" + atividade.getTipoAtividade().getIdTipoAtividade() + "', '" + atividade.getDescricao() + "', " + atividade.getFaseIdFase() + ", " + atividade.getEstado() + ")"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_atividade"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { atividade.setIdAtividade(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
11
Code Sample 1: public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.decrypt(reader, writer, key, mode); } Code Sample 2: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] path = StringUtils.split(request.getRequestURI(), "/"); String file = path[path.length - 1]; File f = new File(pathToImages + "/" + file); response.setContentType(getServletContext().getMimeType(f.getName())); FileInputStream fis = new FileInputStream(f); IOUtils.copy(fis, response.getOutputStream()); fis.close(); }
00
Code Sample 1: public FTPClient sample3c(String ftpserver, int ftpport, String proxyserver, int proxyport, String username, String password) throws SocketException, IOException { FTPHTTPClient ftpClient = new FTPHTTPClient(proxyserver, proxyport); ftpClient.setDefaultPort(ftpport); ftpClient.connect(ftpserver); ftpClient.login(username, password); return ftpClient; } Code Sample 2: public static final boolean compressToZip(final String sSource, final String sDest, final boolean bDeleteSourceOnSuccess) { ZipOutputStream os = null; InputStream is = null; try { os = new ZipOutputStream(new FileOutputStream(sDest)); is = new FileInputStream(sSource); final byte[] buff = new byte[1024]; int r; String sFileName = sSource; if (sFileName.indexOf('/') >= 0) sFileName = sFileName.substring(sFileName.lastIndexOf('/') + 1); os.putNextEntry(new ZipEntry(sFileName)); while ((r = is.read(buff)) > 0) os.write(buff, 0, r); is.close(); os.flush(); os.closeEntry(); os.close(); } catch (Throwable e) { Log.log(Log.WARNING, "lazyj.Utils", "compressToZip : cannot compress '" + sSource + "' to '" + sDest + "' because", e); return false; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } if (os != null) { try { os.close(); } catch (IOException ioe) { } } } if (bDeleteSourceOnSuccess) try { if (!(new File(sSource)).delete()) Log.log(Log.WARNING, "lazyj.Utils", "compressToZip: could not delete original file (" + sSource + ")"); } catch (SecurityException se) { Log.log(Log.ERROR, "lazyj.Utils", "compressToZip: security constraints prevents file deletion"); } return true; }
00
Code Sample 1: public static void s_copy(FileInputStream fis, FileOutputStream fos) throws Exception { FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel(); in.transferTo(0, in.size(), out); if (in != null) in.close(); if (out != null) out.close(); } Code Sample 2: public boolean send(String number, String message) throws IOException { init(); message = message.substring(0, Math.min(MAX_PAYLOAD, message.length())); message = message.replace('\r', ' '); message = message.replace('\n', ' '); ActualFormParameters params = new ActualFormParameters(); String strippedNumber = strip(number); ActualFormParameter number1Param; ActualFormParameter number2Param; if (strippedNumber.startsWith("00")) strippedNumber = "+" + strippedNumber.substring(2); else if (strippedNumber.startsWith("0")) strippedNumber = "+49" + strippedNumber.substring(1); number1Param = new ActualFormParameter(number1InputElement.getName(), strippedNumber.substring(0, 6)); number2Param = new ActualFormParameter(number2InputElement.getName(), strippedNumber.substring(6)); params.add(number1Param); params.add(number2Param); ActualFormParameter messageParam = new ActualFormParameter(messageInputElement.getName(), message); params.add(messageParam); ActualFormParameter letterCountParam = new ActualFormParameter(letterCountInputElement.getName(), "" + (MAX_PAYLOAD - message.length())); params.add(letterCountParam); form.addDefaultParametersTo(params); Reader r = form.submitForm(params, form.getNetscapeRequestProperties()); String result = getStringFromReader(r); String pattern = "<meta http-equiv = \"refresh\" content=\"1; url="; int patternIndex = result.indexOf(pattern); if (patternIndex < 0) return false; int end = result.lastIndexOf("\">"); if (end < 0) return false; String url = result.substring(patternIndex + pattern.length(), end); result = getStringFromReader(new InputStreamReader(new URL(url).openStream())); return result.indexOf("wurde erfolgreich verschickt") >= 0; }
11
Code Sample 1: void IconmenuItem5_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (getPath() != null && !getPath().equals("")) { jFileChooser1.setCurrentDirectory(new File(getPath())); jFileChooser1.setSelectedFile(new File(getPath())); } if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getPath().lastIndexOf(separator); String imgName = getPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setPath(newPath); if (getDefaultPath() == null || getDefaultPath().equals("")) { String msgString = "E' stata selezionata un'immagine da associare all'IconShape, ma non e' " + "stata selezionata ancora nessun'immagine di default. Imposto quella scelta anche come " + "immagine di default?"; if (JOptionPane.showConfirmDialog(null, msgString.substring(0, Math.min(msgString.length(), getFatherPanel().MAX_DIALOG_MSG_SZ)), "choose one", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { setDefaultPath(newPath); createDefaultImage(); } } createImage(); } } 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 void getRandomGUID(boolean secure, Object o) { 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(o.getClass().getName()); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: private void unzipData(ZipFile zipfile, ZipEntry entry) { if (entry.getName().equals("backUpExternalInfo.out")) { File outputFile = new File("temp", entry.getName()); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } try { BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException e) { throw new BackupException(e.getMessage()); } } }
11
Code Sample 1: public static InputStream gunzip(final InputStream inputStream) throws IOException { Assert.notNull(inputStream, "inputStream"); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); InputOutputStream inputOutputStream = new InputOutputStream(); IOUtils.copy(gzipInputStream, inputOutputStream); return inputOutputStream.getInputStream(); } Code Sample 2: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
00
Code Sample 1: private String getMd5(String base64image) { String token = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(base64image.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); token = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return token; } Code Sample 2: public static void main(String[] args) { int dizi[] = { 23, 78, 45, 8, 3, 32, 56, 39, 92, 28 }; boolean test = false; int kars = 0; int tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } for (int i = 0; i < dizi.length; i++) { System.out.print(dizi[i] + " "); } for (int i = 0; i < 5; i++) { System.out.println("i" + i); } }
11
Code Sample 1: public static boolean copyFile(File src, File des) { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(des)); int b; while ((b = in.read()) != -1) out.write(b); out.flush(); out.close(); in.close(); return true; } catch (IOException ie) { m_logCat.error("Copy file + " + src + " to " + des + " failed!", ie); return false; } } Code Sample 2: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
11
Code Sample 1: public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; } Code Sample 2: public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = null; ServletOutputStream outstream = null; try { String action = req.getParameter("nmrshiftdbaction"); String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF"); TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties")); tc.init(); int spectrumId = -1; DBSpectrum spectrum = null; Export export = null; String format = req.getParameter("format"); if (action.equals("test")) { try { res.setContentType("text/plain"); out = res.getWriter(); List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1"); if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt(); out.write("success"); } catch (Exception ex) { out.write("failure"); } } else if (action.equals("rss")) { int numbertoexport = 10; out = res.getWriter(); if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } res.setContentType("text/xml"); RssWriter rssWriter = new RssWriter(); rssWriter.setWriter(res.getWriter()); AtomContainerSet soac = new AtomContainerSet(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;"; List l = NmrshiftdbUserPeer.executeQuery(query); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1); soac.addAtomContainer(cdkmol); rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req)); rssWriter.getDatemap().put(cdkmol, mol.getDate()); rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback()); rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName()); rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig())); Vector v = mol.getDBCanonicalNames(); for (int k = 0; k < v.size(); k++) { DBCanonicalName canonName = (DBCanonicalName) v.get(k); if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") { rssWriter.getInchimap().put(cdkmol, canonName.getName()); break; } } rssWriter.setTitle("NMRShiftDB"); rssWriter.setLink("http://www.nmrshiftdb.org"); rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data"); rssWriter.setPublisher("NMRShiftDB.org"); rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif"); rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss"); Collection coll = new ArrayList(); Vector spectra = mol.selectSpectra(null); for (int k = 0; k < spectra.size(); k++) { Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Element el2 = el.getChildElements().get(0); el.removeChild(el2); coll.add(el2); } rssWriter.getMultiMap().put(cdkmol, coll); } rssWriter.write(soac); } else if (action.equals("getattachment")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid"))); outstream.write(sample.getAttachment()); } else if (action.equals("createreport")) { res.setContentType("application/pdf"); outstream = res.getOutputStream(); boolean yearly = req.getParameter("style").equals("yearly"); int yearstart = Integer.parseInt(req.getParameter("yearstart")); int yearend = Integer.parseInt(req.getParameter("yearend")); int monthstart = 0; int monthend = 0; if (!yearly) { monthstart = Integer.parseInt(req.getParameter("monthstart")); monthend = Integer.parseInt(req.getParameter("monthend")); } int type = Integer.parseInt(req.getParameter("type")); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper"); Map parameters = new HashMap(); if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend); DBConnection dbconn = TurbineDB.getConnection(); Connection conn = dbconn.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; if (type == 1) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME"); } else if (type == 2) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME"); } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs)); JasperExportManager.exportReportToPdfStream(jasperPrint, outstream); dbconn.close(); } else if (action.equals("exportcmlbyinchi")) { res.setContentType("text/xml"); out = res.getWriter(); String inchi = req.getParameter("inchi"); String spectrumtype = req.getParameter("spectrumtype"); Criteria crit = new Criteria(); crit.add(DBCanonicalNamePeer.NAME, inchi); crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID); crit.add(DBSpectrumTypePeer.NAME, spectrumtype); try { GeneralUtils.logToSql(crit.toString(), null); } catch (Exception ex) { } Vector spectra = DBSpectrumPeer.doSelect(crit); if (spectra.size() == 0) { out.write("No such molecule or spectrum"); } else { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); for (int k = 0; k < spectra.size(); k++) { Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); } out.write(cmlElement.toXML()); } } else if (action.equals("namelist")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); Criteria crit = new Criteria(); crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.add(DBSpectrumPeer.REVIEW_FLAG, "true"); Vector v = DBMoleculePeer.doSelect(crit); for (int i = 0; i < v.size(); i++) { if (i % 500 == 0) { if (i != 0) { zipout.write(new String("<p>The list is continued <a href=\"nmrshiftdb.names." + i + ".html\">here</a></p></body></html>").getBytes()); zipout.closeEntry(); } zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html")); zipout.write(new String("<html><body><h1>This is a list of strcutures in <a href=\"http://www.nmrshiftdb.org\">NMRShiftDB</a>, starting at " + i + ", Its main purpose is to be found by search engines</h1>").getBytes()); } DBMolecule mol = (DBMolecule) v.get(i); zipout.write(new String("<p><a href=\"" + mol.getEasylink(req) + "\">").getBytes()); Vector cannames = mol.getDBCanonicalNames(); for (int k = 0; k < cannames.size(); k++) { zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes()); } Vector chemnames = mol.getDBChemicalNames(); for (int k = 0; k < chemnames.size(); k++) { zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes()); } zipout.write(new String("</a>. Information we have got: NMR spectra").getBytes()); Vector spectra = mol.selectSpectra(); for (int k = 0; k < spectra.size(); k++) { zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes()); } if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes()); zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes()); zipout.write(new String("</p>").getBytes()); } zipout.write(new String("</body></html>").getBytes()); zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("predictor")) { if (req.getParameter("symbol") == null) { res.setContentType("text/plain"); out = res.getWriter(); out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C"); } res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); String filename = "org/openscience/nmrshiftdb/PredictionTool.class"; zipout.putNextEntry(new ZipEntry(filename)); JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar"))); JarEntry entry = jip.getNextJarEntry(); while (entry.getName().indexOf("PredictionTool.class") == -1) { entry = jip.getNextJarEntry(); } for (int i = 0; i < entry.getSize(); i++) { zipout.write(jip.read()); } zipout.closeEntry(); zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv")); int i = 0; org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection(); HashMap mapsmap = new HashMap(); while (true) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000"); int m = 0; while (rs.next()) { String code = rs.getString(1); Double value = new Double(rs.getString(2)); String symbol = rs.getString(3); if (mapsmap.get(symbol) == null) { mapsmap.put(symbol, new HashMap()); } for (int spheres = 6; spheres > 0; spheres--) { StringBuffer hoseCodeBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(code, "()/"); for (int k = 0; k < spheres; k++) { if (st.hasMoreTokens()) { String partcode = st.nextToken(); hoseCodeBuffer.append(partcode); } if (k == 0) { hoseCodeBuffer.append("("); } else if (k == 3) { hoseCodeBuffer.append(")"); } else { hoseCodeBuffer.append("/"); } } String hoseCode = hoseCodeBuffer.toString(); if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) { ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList()); } ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value); } m++; } i++; stmt.close(); if (m == 0) break; } Set keySet = mapsmap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String symbol = (String) it.next(); HashMap hosemap = ((HashMap) mapsmap.get(symbol)); Set keySet2 = hosemap.keySet(); Iterator it2 = keySet2.iterator(); while (it2.hasNext()) { String hoseCode = (String) it2.next(); ArrayList list = ((ArrayList) hosemap.get(hoseCode)); double[] values = new double[list.size()]; for (int k = 0; k < list.size(); k++) { values[k] = ((Double) list.get(k)).doubleValue(); } zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes()); } } zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; i = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("exportspec") || action.equals("exportmol")) { if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid"))); export = new Export(spectrum); } else if (action.equals("exportmdl")) { res.setContentType("text/plain"); outstream = res.getOutputStream(); DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid"))); outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes()); } else if (action.equals("exportlastinputs")) { format = action; } else if (action.equals("printpredict")) { res.setContentType("text/html"); out = res.getWriter(); HttpSession session = req.getSession(); VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true); StringWriter w = new StringWriter(); Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w); out.println(w.toString()); } else { res.setContentType("text/html"); out = res.getWriter(); out.println("No valid action"); } if (format == null) format = ""; if (format.equals("pdf") || format.equals("rtf")) { res.setContentType("application/" + format); out = res.getWriter(); } if (format.equals("docbook")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); } if (format.equals("svg")) { res.setContentType("image/x-svg"); out = res.getWriter(); } if (format.equals("tiff")) { res.setContentType("image/tiff"); outstream = res.getOutputStream(); } if (format.equals("jpeg")) { res.setContentType("image/jpeg"); outstream = res.getOutputStream(); } if (format.equals("png")) { res.setContentType("image/png"); outstream = res.getOutputStream(); } if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) { res.setContentType("text/plain"); out = res.getWriter(); } if (format.equals("simplehtml") || format.equals("exportlastinputs")) { res.setContentType("text/html"); out = res.getWriter(); } if (action.equals("exportlastinputs")) { int numbertoexport = 4; if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } NmrshiftdbUser user = null; try { user = NmrshiftdbUserPeer.getByName(req.getParameter("username")); } catch (NmrshiftdbException ex) { out.println("Seems <code>username</code> is not OK: " + ex.getMessage()); } if (user != null) { List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER where LOGIN_NAME=\"" + user.getUserName() + "\";"); Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate(); if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) { out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!"); } else { NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";"); Vector<String> parameters = new Vector<String>(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;"; l = NmrshiftdbUserPeer.executeQuery(query); String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString(); url = url.substring(0, url.length() - 17); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); parameters.add(new String("<a href=\"" + url + "/portal/pane0/Results?nmrshiftdbaction=showDetailsFromHome&molNumber=" + mol.getMoleculeId() + "\"><img src=\"" + javax.servlet.http.HttpUtils.getRequestURL(req).toString() + "?nmrshiftdbaction=exportmol&spectrumid=" + ((DBSpectrum) mol.getDBSpectrums().get(0)).getSpectrumId() + "&format=jpeg&size=150x150&backcolor=12632256\"></a>")); } VelocityContext context = new VelocityContext(); context.put("results", parameters); StringWriter w = new StringWriter(); Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w); out.println(w.toString()); } } } if (action.equals("exportspec")) { if (format.equals("txt")) { String lastsearchtype = req.getParameter("lastsearchtype"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues")); spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)); } Vector v = spectrum.getOptions(); DBMolecule mol = spectrum.getDBMolecule(); out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r"); out.print("\n\rAtom\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t"); out.print("Meas."); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tInput\tDiff"); } out.print("\n\r"); out.print("No.\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t"); out.print("Shift"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tShift\tM-I"); } out.print("\n\r"); for (int i = 0; i < v.size(); i++) { out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange()); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta()); } out.print("\n\r"); } } if (format.equals("simplehtml")) { String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[0] = new File(i1).getName(); String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[1] = new File(i2).getName(); String docbook = export.getHtml(); out.print(docbook); } if (format.equals("pdf") || format.equals("rtf")) { String svgSpec = export.getSpecSvg(400, 200); String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg"; new FileOutputStream(svgspecfile).write(svgSpec.getBytes()); export.pictures[1] = svgspecfile; String molSvg = export.getMolSvg(true); String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg"; new FileOutputStream(svgmolfile).write(molSvg.getBytes()); export.pictures[0] = svgmolfile; String docbook = export.getDocbook("pdf", "SVG"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos)); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out2 = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2); TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); Source src = new StreamSource(new StringReader(baos.toString())); Result res2 = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res2); out.print(out2.toString()); } if (format.equals("docbook")) { String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes()); export.pictures[0] = new File(i1).getName(); String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i2).write(export.getMolSvg(true).getBytes()); export.pictures[1] = new File(i2).getName(); String docbook = export.getDocbook("pdf", "SVG"); String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml"; new FileOutputStream(docbookfile).write(docbook.getBytes()); ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 }); outstream.write(baos.toByteArray()); } if (format.equals("svg")) { out.print(export.getSpecSvg(400, 200)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("cml")) { out.print(spectrum.getCmlSpect().toXML()); } if (format.equals("cmlboth")) { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H")); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); Element parentspec = spectrum.getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); out.write(cmlElement.toXML()); } if (format.indexOf("exsection") == 0) { StringTokenizer st = new StringTokenizer(format, "-"); st.nextToken(); String template = st.nextToken(); Criteria crit = new Criteria(); crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId()); Vector v = spectrum.getDBMolecule().getDBSpectrums(crit); VelocityContext context = new VelocityContext(); context.put("spectra", v); context.put("molecule", spectrum.getDBMolecule()); StringWriter w = new StringWriter(); Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w); out.write(w.toString()); } } if (action.equals("exportmol")) { int width = -1; int height = -1; if (req.getParameter("size") != null) { StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x"); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } boolean shownumbers = true; if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) { shownumbers = false; } if (req.getParameter("backcolor") != null) { export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor"))); } if (req.getParameter("markatom") != null) { export.selected = Integer.parseInt(req.getParameter("markatom")) - 1; } if (format.equals("svg")) { out.print(export.getMolSvg(true)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("mdl")) { out.println(spectrum.getDBMolecule().getStructureFile(1, false)); } if (format.equals("cml")) { out.println(spectrum.getDBMolecule().getCMLString(1)); } } if (out != null) out.flush(); else outstream.flush(); } catch (Exception ex) { ex.printStackTrace(); out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true)); out.flush(); } }
11
Code Sample 1: @org.junit.Test public void testReadWrite() throws Exception { final String reference = "testString"; final Reader reader = new StringReader(reference); final StringWriter osString = new StringWriter(); final Reader teeStream = new TeeReaderWriter(reader, osString); IOUtils.copy(teeStream, new NullWriter()); teeStream.close(); osString.toString(); } 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; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
00
Code Sample 1: public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
00
Code Sample 1: public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); } Code Sample 2: public static void copyFile(File src, File dest, boolean notifyUserOnError) { if (src.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } catch (IOException e) { String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } else { String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } }
11
Code Sample 1: public static String md5Encrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] md5hash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } md5hash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < md5hash.length; i++) { if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; } Code Sample 2: public static synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
11
Code Sample 1: public static void copy(FileInputStream from, FileOutputStream to) throws IOException { FileChannel fromChannel = from.getChannel(); FileChannel toChannel = to.getChannel(); copy(fromChannel, toChannel); fromChannel.close(); toChannel.close(); } Code Sample 2: public Object process(Atom oAtm) throws IOException { File oFile; FileReader oFileRead; String sPathHTML; char cBuffer[]; Object oReplaced; final String sSep = System.getProperty("file.separator"); if (DebugFile.trace) { DebugFile.writeln("Begin FileDumper.process([Job:" + getStringNull(DB.gu_job, "") + ", Atom:" + String.valueOf(oAtm.getInt(DB.pg_atom)) + "])"); DebugFile.incIdent(); } if (bHasReplacements) { sPathHTML = getProperty("workareasput"); if (!sPathHTML.endsWith(sSep)) sPathHTML += sSep; sPathHTML += getParameter("gu_workarea") + sSep + "apps" + sSep + "Mailwire" + sSep + "html" + sSep + getParameter("gu_pageset") + sSep; sPathHTML += getParameter("nm_pageset").replace(' ', '_') + ".html"; if (DebugFile.trace) DebugFile.writeln("PathHTML = " + sPathHTML); oReplaced = oReplacer.replace(sPathHTML, oAtm.getItemMap()); bHasReplacements = (oReplacer.lastReplacements() > 0); } else { oReplaced = null; if (null != oFileStr) oReplaced = oFileStr.get(); if (null == oReplaced) { sPathHTML = getProperty("workareasput"); if (!sPathHTML.endsWith(sSep)) sPathHTML += sSep; sPathHTML += getParameter("gu_workarea") + sSep + "apps" + sSep + "Mailwire" + sSep + "html" + sSep + getParameter("gu_pageset") + sSep + getParameter("nm_pageset").replace(' ', '_') + ".html"; if (DebugFile.trace) DebugFile.writeln("PathHTML = " + sPathHTML); oFile = new File(sPathHTML); cBuffer = new char[new Long(oFile.length()).intValue()]; oFileRead = new FileReader(oFile); oFileRead.read(cBuffer); oFileRead.close(); if (DebugFile.trace) DebugFile.writeln(String.valueOf(cBuffer.length) + " characters readed"); oReplaced = new String(cBuffer); oFileStr = new SoftReference(oReplaced); } } String sPathJobDir = getProperty("storage"); if (!sPathJobDir.endsWith(sSep)) sPathJobDir += sSep; sPathJobDir += "jobs" + sSep + getParameter("gu_workarea") + sSep + getString(DB.gu_job) + sSep; FileWriter oFileWrite = new FileWriter(sPathJobDir + getString(DB.gu_job) + "_" + String.valueOf(oAtm.getInt(DB.pg_atom)) + ".html", true); oFileWrite.write((String) oReplaced); oFileWrite.close(); iPendingAtoms--; if (DebugFile.trace) { DebugFile.writeln("End FileDumper.process([Job:" + getStringNull(DB.gu_job, "") + ", Atom:" + String.valueOf(oAtm.getInt(DB.pg_atom)) + "])"); DebugFile.decIdent(); } return oReplaced; }
11
Code Sample 1: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); } Code Sample 2: public static boolean copyFile(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) return false; if (sourceFileName.equals(destFileName)) return false; try { java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); try { byte[] buf = new byte[31000]; int read = in.read(buf); while (read > -1) { out.write(buf, 0, read); read = in.read(buf); } } finally { in.close(); out.close(); } } catch (Exception e) { System.out.println(e.toString()); return false; } return true; }
11
Code Sample 1: public static void copy(File source, File target) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER); while (in.read(buffer) != -1) { buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } buffer.clear(); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { close(in); close(out); } } Code Sample 2: public String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; }
11
Code Sample 1: public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: public static boolean encodeFileToFile(final String infile, final 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)); final byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (final java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (final Exception exc) { } try { out.close(); } catch (final Exception exc) { } } return success; } Code Sample 2: private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
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 String fileUpload(final ResourceType type, final String currentFolder, final String fileName, final InputStream inputStream) throws InvalidCurrentFolderException, WriteException { String absolutePath = getRealUserFilesAbsolutePath(RequestCycleHandler.getUserFilesAbsolutePath(ThreadLocalData.getRequest())); File typeDir = getOrCreateResourceTypeDir(absolutePath, type); File currentDir = new File(typeDir, currentFolder); if (!currentDir.exists() || !currentDir.isDirectory()) throw new InvalidCurrentFolderException(); File newFile = new File(currentDir, fileName); File fileToSave = UtilsFile.getUniqueFile(newFile.getAbsoluteFile()); try { IOUtils.copyLarge(inputStream, new FileOutputStream(fileToSave)); } catch (IOException e) { throw new WriteException(); } return fileToSave.getName(); }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentType = req.getParameter("type"); String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing File Arg"); return; } File f = new File(arg); if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } if (contentType != null) { resp.setContentType(contentType); } log.debug("Requested File: " + f + " as type: " + contentType); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } } Code Sample 2: private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); }