label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: @Override protected IStatus run(final IProgressMonitor monitor) { try { showTileInfo(remoteFileName, -1); System.out.println(" connect " + host); ftp.connect(); showTileInfo(remoteFileName, -2); System.out.println(" login " + user + " " + password); ftp.login(user, password); System.out.println(" set passive mode"); ftp.setConnectMode(FTPConnectMode.PASV); System.out.println(" set type binary"); ftp.setType(FTPTransferType.BINARY); showTileInfo(remoteFileName, -3); System.out.println(" chdir " + remoteFilePath); ftp.chdir(remoteFilePath); ftp.setProgressMonitor(new FTPProgressMonitor() { public void bytesTransferred(final long count) { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_LOADING_MONITOR, remoteFileName, count); } }); showTileInfo(remoteFileName, -4); System.out.println(" get " + remoteFileName + " -> " + localName + " ..."); ftp.get(localName, remoteFileName); System.out.println(" quit"); ftp.quit(); } catch (final UnknownHostException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_cannotConnectToServer, host), e); } catch (final SocketTimeoutException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_timeoutWhenConnectingToServer, host), e); } catch (final Exception e) { e.printStackTrace(); tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_ERROR_LOADING, remoteFileName, 0); } finally { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_END_LOADING, remoteFileName, 0); } return Status.OK_STATUS; } Code Sample 2: private String callPage(String urlStr) throws IOException { URL url = new URL(urlStr); BufferedReader reader = null; StringBuilder result = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } } finally { if (reader != null) reader.close(); } return result.toString(); }
11
Code Sample 1: @TestTargets({ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies that the ObjectInputStream constructor calls checkPermission on security manager.", method = "ObjectInputStream", args = { InputStream.class }) }) public void test_ObjectInputStream2() throws IOException { class TestSecurityManager extends SecurityManager { boolean called; Permission permission; void reset() { called = false; permission = null; } @Override public void checkPermission(Permission permission) { if (permission instanceof SerializablePermission) { called = true; this.permission = permission; } } } class TestObjectInputStream extends ObjectInputStream { TestObjectInputStream(InputStream s) throws StreamCorruptedException, IOException { super(s); } } class TestObjectInputStream_readFields extends ObjectInputStream { TestObjectInputStream_readFields(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public GetField readFields() throws IOException, ClassNotFoundException, NotActiveException { return super.readFields(); } } class TestObjectInputStream_readUnshared extends ObjectInputStream { TestObjectInputStream_readUnshared(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public Object readUnshared() throws IOException, ClassNotFoundException { return super.readUnshared(); } } long id = new java.util.Date().getTime(); String filename = "SecurityPermissionsTest_" + id; File f = File.createTempFile(filename, null); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(new Node()); oos.flush(); oos.close(); f.deleteOnExit(); TestSecurityManager s = new TestSecurityManager(); System.setSecurityManager(s); s.reset(); new ObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream_readFields(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readFields", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); s.reset(); new TestObjectInputStream_readUnshared(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readUnshared", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); } Code Sample 2: public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); XSLTBuddy buddy = new XSLTBuddy(); buddy.parseArgs(args); XSLTransformer transformer = new XSLTransformer(); if (buddy.templateDir != null) { transformer.setTemplateDir(buddy.templateDir); } FileReader xslReader = new FileReader(buddy.xsl); Templates xslTemplate = transformer.getXSLTemplate(buddy.xsl, xslReader); for (Enumeration e = buddy.params.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); transformer.addParam(key, buddy.params.get(key)); } Reader reader = null; if (buddy.src == null) { reader = new StringReader(XSLTBuddy.BLANK_XML); } else { reader = new FileReader(buddy.src); } if (buddy.out == null) { String result = transformer.doTransform(reader, xslTemplate, buddy.xsl); buddy.getLogger().info("\n\nXSLT Result:\n\n" + result + "\n"); } else { File file = new File(buddy.out); File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); } FileWriter writer = new FileWriter(buddy.out); transformer.doTransform(reader, xslTemplate, buddy.xsl, writer); writer.flush(); writer.close(); } buddy.getLogger().info("Transform done successfully in " + (System.currentTimeMillis() - start) + " milliseconds"); }
00
Code Sample 1: public String getMessageofTheDay(String id) { StringBuffer mod = new StringBuffer(); int serverModId = 0; int clientModId = 0; BufferedReader input = null; try { URL url = new URL(FlyShareApp.BASE_WEBSITE_URL + "/mod.txt"); input = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; inputLine = input.readLine(); try { clientModId = Integer.parseInt(id); serverModId = Integer.parseInt(inputLine); } catch (NumberFormatException e) { } if (clientModId < serverModId || clientModId == 0) { mod.append(serverModId); mod.append('|'); while ((inputLine = input.readLine()) != null) mod.append(inputLine); } } catch (MalformedURLException e) { } catch (IOException e) { } finally { try { input.close(); } catch (Exception e) { } } return mod.toString(); } Code Sample 2: private void handleInterfaceReparented(String ipAddr, Parms eventParms) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (log.isDebugEnabled()) log.debug("interfaceReparented event received..."); if (ipAddr == null || eventParms == null) { log.warn(EventConstants.INTERFACE_REPARENTED_EVENT_UEI + " ignored - info incomplete - ip/parms: " + ipAddr + "/" + eventParms); return; } long oldNodeId = -1; long newNodeId = -1; String parmName = null; Value parmValue = null; String parmContent = null; Enumeration parmEnum = eventParms.enumerateParm(); while (parmEnum.hasMoreElements()) { Parm parm = (Parm) parmEnum.nextElement(); parmName = parm.getParmName(); parmValue = parm.getValue(); if (parmValue == null) continue; else parmContent = parmValue.getContent(); if (parmName.equals(EventConstants.PARM_OLD_NODEID)) { try { oldNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_OLD_NODEID + " cannot be non-numeric"); oldNodeId = -1; } } else if (parmName.equals(EventConstants.PARM_NEW_NODEID)) { try { newNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_NEW_NODEID + " cannot be non-numeric"); newNodeId = -1; } } } if (newNodeId == -1 || oldNodeId == -1) { log.warn("Unable to process 'interfaceReparented' event, invalid event parm."); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement reparentOutagesStmt = dbConn.prepareStatement(OutageConstants.DB_REPARENT_OUTAGES); reparentOutagesStmt.setLong(1, newNodeId); reparentOutagesStmt.setLong(2, oldNodeId); reparentOutagesStmt.setString(3, ipAddr); int count = reparentOutagesStmt.executeUpdate(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Reparented " + count + " outages - ip: " + ipAddr + " reparented from " + oldNodeId + " to " + newNodeId); } catch (SQLException se) { log.warn("Rolling back transaction, reparent outages failed for newNodeId/ipAddr: " + newNodeId + "/" + ipAddr); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } reparentOutagesStmt.close(); } catch (SQLException se) { log.warn("SQL exception while handling \'interfaceReparented\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
11
Code Sample 1: public static String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } md.update(plaintext.getBytes(Charset.defaultCharset())); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
00
Code Sample 1: public URLConnection makeURLcon() { URI uri; URL url; try { uri = new URI(this.URLString); url = uri.toURL(); this.urlcon = (HttpURLConnection) url.openConnection(); } catch (final URISyntaxException e) { e.printStackTrace(); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } return this.urlcon; } Code Sample 2: public static ArrayList<Quote> fetchAllQuotes(String symbol, Date from, Date to) { try { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(from); String monthFrom = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayFrom = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearFrom = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); calendar.setTime(to); String monthTo = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayTo = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearTo = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + monthFrom + "&b=" + dayFrom + "&c=" + yearFrom + "&d=" + monthTo + "&e=" + dayTo + "&f=" + yearTo + "&g=d&ignore=.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; ArrayList<Quote> result = new ArrayList<Quote>(); reader.readLine(); while ((line = reader.readLine()) != null) { String[] values = line.split(","); String date = values[0]; Date dateQuote = new SimpleDateFormat("yyyy-MM-dd").parse(date); double open = Double.valueOf(values[1]); double high = Double.valueOf(values[2]); double low = Double.valueOf(values[3]); double close = Double.valueOf(values[4]); long volume = Long.valueOf(values[5]); double adjClose = Double.valueOf(values[6]); Quote q = new Quote(dateQuote, open, high, low, close, volume, adjClose); result.add(q); } reader.close(); Collections.reverse(result); return result; } catch (MalformedURLException e) { System.out.println("URL malformee"); } catch (IOException e) { System.out.println("Donnees illisibles"); } catch (ParseException e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static String hash(String password) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(password.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuilder hexString = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } Code Sample 2: @Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } }
00
Code Sample 1: public boolean save(Object obj) { boolean bool = false; this.result = null; if (obj == null) return bool; Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, obj); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; } Code Sample 2: public static String getFurigana(String sentence) throws Exception { Log.d("--VOA--", "getFurigana START"); sbFurigana = new StringBuffer(); String urlStr = getYahooApiURL(); urlStr = addSentence(urlStr, sentence); URL url = new URL(urlStr); URLConnection uc = url.openConnection(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Log.d("--VOA--", uc.getURL().toString()); InputStream is = uc.getInputStream(); doc = db.parse(is); walkThrough(); Log.d("--VOA--", "getFurigana END"); return sbFurigana.toString(); }
11
Code Sample 1: private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; } Code Sample 2: public void run() { Vector<Update> updates = new Vector<Update>(); if (dic != null) updates.add(dic); if (gen != null) updates.add(gen); if (res != null) updates.add(res); if (help != null) updates.add(help); for (Iterator iterator = updates.iterator(); iterator.hasNext(); ) { Update update = (Update) iterator.next(); try { File temp = File.createTempFile("fm_" + update.getType(), ".jar"); temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); URL url = new URL(update.getAction()); URLConnection conn = url.openConnection(); com.diccionarioderimas.Utils.setupProxy(conn); InputStream in = conn.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; int total = 0; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); total += read; if (total > 10000) { progressBar.setValue(progressBar.getValue() + total); total = 0; } } out.close(); in.close(); String fileTo = basePath + "diccionariorimas.jar"; if (update.getType() == Update.GENERATOR) fileTo = basePath + "generador.jar"; else if (update.getType() == Update.RESBC) fileTo = basePath + "resbc.me"; else if (update.getType() == Update.HELP) fileTo = basePath + "help.html"; if (update.getType() == Update.RESBC) { Utils.unzip(temp, new File(fileTo)); } else { Utils.copyFile(new FileInputStream(temp), new File(fileTo)); } } catch (Exception e) { e.printStackTrace(); } } setVisible(false); if (gen != null || res != null) { try { new Main(null, basePath, false); } catch (Exception e) { new ErrorDialog(frame, e); } } String restart = ""; if (dic != null) restart += "\nAlgunas de ellas s�lo estar�n disponibles despu�s de reiniciar el diccionario."; JOptionPane.showMessageDialog(frame, "Se han terminado de realizar las actualizaciones." + restart, "Actualizaciones", JOptionPane.INFORMATION_MESSAGE); }
11
Code Sample 1: 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) { ; } } } Code Sample 2: public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = DefaultXmlFieldSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile, boolean overwrite) throws IOException, DirNotFoundException, FileNotFoundException, FileExistsAlreadyException { File destDir = new File(destFile.getParent()); if (!destDir.exists()) { throw new DirNotFoundException(destDir.getAbsolutePath()); } if (!sourceFile.exists()) { throw new FileNotFoundException(sourceFile.getAbsolutePath()); } if (!overwrite && destFile.exists()) { throw new FileExistsAlreadyException(destFile.getAbsolutePath()); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
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 compress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(srcFile)); output = new GZIPOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
00
Code Sample 1: public TVRageShowInfo(String xmlShowName, String xmlSearchBy) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime") && tmp.length > 1) { airTime = tmp[1]; } } if (airTime.length() > 10) { tmp = airTime.split("at"); airTimeHour = tmp[1]; } in.close(); if (xmlSearchBy.equals("Showname SeriesNum")) { url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[5].indexOf(':') > -1) { tmp = tmp[5].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[3].indexOf(':') > -1) { tmp = tmp[3].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public void removeDownload() { synchronized (mDownloadMgr) { int rowCount = mDownloadTable.getSelectedRowCount(); if (rowCount <= 0) return; int[] rows = mDownloadTable.getSelectedRows(); int[] orderedRows = new int[rows.length]; Vector downloadFilesToRemove = new Vector(); for (int i = 0; i < rowCount; i++) { int row = rows[i]; if (row >= mDownloadMgr.getDownloadCount()) return; orderedRows[i] = mDownloadSorter.indexes[row]; } mDownloadTable.removeRowSelectionInterval(0, mDownloadTable.getRowCount() - 1); for (int i = orderedRows.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (orderedRows[j] > orderedRows[j + 1]) { int tmp = orderedRows[j]; orderedRows[j] = orderedRows[j + 1]; orderedRows[j + 1] = tmp; } } } for (int i = orderedRows.length - 1; i >= 0; i--) { mDownloadMgr.removeDownload(orderedRows[i]); } mainFrame.refreshAllActions(); } }
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: @Test public void testWriteModel() { Model model = new Model(); model.setName("MY_MODEL1"); Stereotype st1 = new Stereotype(); st1.setName("Pirulito1"); PackageObject p1 = new PackageObject("p1"); ClassType type1 = new ClassType("Class1"); type1.setStereotype(st1); type1.addMethod(new Method("doSomething")); p1.add(type1); ClassType type2 = new ClassType("Class2"); Method m2 = new Method("doSomethingElse"); m2.setType(type1); type2.addMethod(m2); p1.add(type2); Generalization g = new Generalization(); g.setSource(type1); g.setTarget(type1); p1.add(g); model.add(p1); ModelWriter writer = new ModelWriter(); try { File modelFile = new File("target", "test.model"); writer.write(model, modelFile); File xmlFile = new File("target", "test.xml"); xmlFile.createNewFile(); IOUtils.copy(new GZIPInputStream(new FileInputStream(modelFile)), new FileOutputStream(xmlFile)); } catch (IOException e) { log.error(e.getMessage(), e); Assert.fail(e.getMessage()); } }
11
Code Sample 1: @Override public void execute() throws ProcessorExecutionException { try { if (getSource().getPaths() == null || getSource().getPaths().size() == 0 || getDestination().getPaths() == null || getDestination().getPaths().size() == 0) { throw new ProcessorExecutionException("No input and/or output paths specified."); } String temp_dir_prefix = getDestination().getPath().getParent().toString() + "/bcc_" + getDestination().getPath().getName() + "_"; SequenceTempDirMgr dirMgr = new SequenceTempDirMgr(temp_dir_prefix, context); dirMgr.setSeqNum(0); Path tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to AdjSetVertex"); Transformer transformer = new OutAdjVertex2AdjSetVertexTransformer(); transformer.setConf(context); transformer.setSrcPath(getSource().getPath()); tmpDir = dirMgr.getTempDir(); transformer.setDestPath(tmpDir); transformer.setMapperNum(getMapperNum()); transformer.setReducerNum(getReducerNum()); transformer.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to LabeledAdjSetVertex"); Vertex2LabeledTransformer l_transformer = new Vertex2LabeledTransformer(); l_transformer.setConf(context); l_transformer.setSrcPath(tmpDir); tmpDir = dirMgr.getTempDir(); l_transformer.setDestPath(tmpDir); l_transformer.setMapperNum(getMapperNum()); l_transformer.setReducerNum(getReducerNum()); l_transformer.setOutputValueClass(LabeledAdjSetVertex.class); l_transformer.execute(); Graph src; Graph dest; Path path_to_remember = tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": SpanningTreeRootChoose"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); GraphAlgorithm choose_root = new SpanningTreeRootChoose(); choose_root.setConf(context); choose_root.setSource(src); choose_root.setDestination(dest); choose_root.setMapperNum(getMapperNum()); choose_root.setReducerNum(getReducerNum()); choose_root.execute(); Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); String root_vertex_id = the_line.substring(SpanningTreeRootChoose.SPANNING_TREE_ROOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("++++++> Chosen the root of spanning tree = " + root_vertex_id); while (true) { System.out.println("++++++>" + dirMgr.getSeqNum() + " Generate the spanning tree rooted at : (" + root_vertex_id + ") from " + tmpDir); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); path_to_remember = tmpDir; GraphAlgorithm spanning = new SpanningTreeGenerate(); spanning.setConf(context); spanning.setSource(src); spanning.setDestination(dest); spanning.setMapperNum(getMapperNum()); spanning.setReducerNum(getReducerNum()); spanning.setParameter(ConstantLabels.ROOT_ID, root_vertex_id); spanning.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + " Test spanning convergence"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm conv_tester = new SpanningConvergenceTest(); conv_tester.setConf(context); conv_tester.setSource(src); conv_tester.setDestination(dest); conv_tester.setMapperNum(getMapperNum()); conv_tester.setReducerNum(getReducerNum()); conv_tester.execute(); long vertexes_out_of_tree = MRConsoleReader.getMapOutputRecordNum(conv_tester.getFinalStatus()); System.out.println("++++++> number of vertexes out of the spanning tree = " + vertexes_out_of_tree); if (vertexes_out_of_tree == 0) { break; } } System.out.println("++++++> From spanning tree to sets of edges"); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm tree2set = new Tree2EdgeSet(); tree2set.setConf(context); tree2set.setSource(src); tree2set.setDestination(dest); tree2set.setMapperNum(getMapperNum()); tree2set.setReducerNum(getReducerNum()); tree2set.execute(); long map_input_records_num = -1; long map_output_records_num = -2; Stack<Path> expanding_stack = new Stack<Path>(); do { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorJoin"); GraphAlgorithm minorjoin = new EdgeSetMinorJoin(); minorjoin.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorjoin.setSource(src); minorjoin.setDestination(dest); minorjoin.setMapperNum(getMapperNum()); minorjoin.setReducerNum(getReducerNum()); minorjoin.execute(); expanding_stack.push(tmpDir); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetJoin"); GraphAlgorithm join = new EdgeSetJoin(); join.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); join.setSource(src); join.setDestination(dest); join.setMapperNum(getMapperNum()); join.setReducerNum(getReducerNum()); join.execute(); map_input_records_num = MRConsoleReader.getMapInputRecordNum(join.getFinalStatus()); map_output_records_num = MRConsoleReader.getMapOutputRecordNum(join.getFinalStatus()); System.out.println("++++++> map in/out : " + map_input_records_num + "/" + map_output_records_num); } while (map_input_records_num != map_output_records_num); while (expanding_stack.size() > 0) { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetExpand"); GraphAlgorithm expand = new EdgeSetExpand(); expand.setConf(context); src = new Graph(Graph.defaultGraph()); src.addPath(expanding_stack.pop()); src.addPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); expand.setSource(src); expand.setDestination(dest); expand.setMapperNum(getMapperNum()); expand.setReducerNum(getReducerNum()); expand.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorExpand"); GraphAlgorithm minorexpand = new EdgeSetMinorExpand(); minorexpand.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorexpand.setSource(src); minorexpand.setDestination(dest); minorexpand.setMapperNum(getMapperNum()); minorexpand.setReducerNum(getReducerNum()); minorexpand.execute(); } System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetSummarize"); GraphAlgorithm summarize = new EdgeSetSummarize(); summarize.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); dest.setPath(getDestination().getPath()); summarize.setSource(src); summarize.setDestination(dest); summarize.setMapperNum(getMapperNum()); summarize.setReducerNum(getReducerNum()); summarize.execute(); dirMgr.deleteAll(); } catch (IOException e) { throw new ProcessorExecutionException(e); } catch (IllegalAccessException e) { throw new ProcessorExecutionException(e); } } Code Sample 2: public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
00
Code Sample 1: public FTPClient sample1(String server, int port, String username, String password) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); return ftpClient; } Code Sample 2: public static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException { GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile)); File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); FileOutputStream fos = new FileOutputStream(outFile); byte[] buf = new byte[100000]; int len; while ((len = gin.read(buf)) > 0) fos.write(buf, 0, len); gin.close(); fos.close(); if (deleteGzipfileOnSuccess) infile.delete(); return outFile; }
11
Code Sample 1: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: destination file is unwriteable: " + toFileName); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
11
Code Sample 1: public FileOutputStream transfer(File from, File to, long mark) throws IOException, InterruptedException { if (out != null) { close(); } FileChannel fch = new FileInputStream(from).getChannel(); FileChannel rollch = new FileOutputStream(to).getChannel(); long size = mark; int count = 0; try { while ((count += rollch.transferFrom(fch, count, size - count)) < size) { } } finally { fch.close(); rollch.close(); } out = create(to); return out; } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
00
Code Sample 1: public ActionResponse executeAction(ActionRequest request) throws Exception { BufferedReader in = null; try { CurrencyEntityManager em = new CurrencyEntityManager(); String id = (String) request.getProperty("ID"); CurrencyMonitor cm = getCurrencyMonitor(em, Long.valueOf(id)); String code = cm.getCode(); if (code == null || code.length() == 0) code = DEFAULT_SYMBOL; String tmp = URL.replace("@", code); ActionResponse resp = new ActionResponse(); URL url = new URL(tmp); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int status = conn.getResponseCode(); if (status == 200) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder value = new StringBuilder(); while (true) { String line = in.readLine(); if (line == null) break; value.append(line); } cm.setLastUpdateValue(new BigDecimal(value.toString())); cm.setLastUpdateTs(new Date()); em.updateCurrencyMonitor(cm); resp.addResult("CURRENCYMONITOR", cm); } else { resp.setErrorCode(ActionResponse.GENERAL_ERROR); resp.setErrorMessage("HTTP Error [" + status + "]"); } return resp; } catch (Exception e) { String st = MiscUtils.stackTrace2String(e); logger.error(st); throw e; } finally { if (in != null) { in.close(); } } } Code Sample 2: public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpMethod httpMethod; if (isPost || isPut) { EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e) : new InputStreamRequestEntity(e, Long.parseLong(length))); excerpt = e.getExcerpt(); } httpMethod = entityEnclosingMethod; } else if (isDelete) { httpMethod = new DeleteMethod(url); } else { httpMethod = new GetMethod(url); } for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { httpMethod.setFollowRedirects(Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value)); } } for (Map.Entry<String, String> header : request.headers) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString())); client.executeMethod(httpMethod); return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset()); }
11
Code Sample 1: private void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } }
00
Code Sample 1: public static void main(String[] argv) throws Exception { Map args = parseOpts(argv); if (args.get("help") != null) { printUsage(); System.exit(0); } else if (args.get("version") != null) { System.out.println("SISC - The Second Interpreter of Scheme Code - " + Util.VERSION); System.exit(0); } Properties props = new Properties(); String configFile = (String) args.get("properties"); if (configFile != null) { try { URL url = Util.url(configFile); URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(false); props.load(conn.getInputStream()); } catch (MalformedURLException e) { System.err.println("WARNING: " + e.getMessage()); } catch (IOException e) { System.err.println("WARNING: " + e.getMessage()); } } AppContext ctx = new AppContext(props); Context.setDefaultAppContext(ctx); URL heap = AppContext.findHeap(Util.makeURL((String) args.get("heap"))); if (heap == null) { System.err.println(Util.liMessage(Util.SISCB, "heapnotfound")); return; } if (!ctx.addHeap(AppContext.openHeap(heap))) return; Interpreter r = Context.enter(ctx); boolean filesLoadedSuccessfully = r.loadSourceFiles((String[]) ((Vector) args.get("files")).toArray(new String[0])); boolean noRepl = args.get("no-repl") != null; boolean call = args.get("call-with-args") != null; int returnCode = 0; String expr = (String) args.get("eval"); if (expr != null) { Value v = Util.VOID; try { v = r.eval(expr); if (!call) System.out.println(v); } catch (SchemeException se) { se.printStackTrace(); returnCode = 1; } } String func = (String) args.get("call-with-args"); if (func != null) { Procedure fun = null; try { fun = Util.proc(r.eval(func)); } catch (SchemeException se) { se.printStackTrace(); returnCode = 1; } if (fun != null) { Vector av = (Vector) args.get("argv"); Value[] sargs = new Value[(av == null ? 0 : av.size())]; for (int i = 0; i < sargs.length; i++) sargs[i] = new SchemeString((String) av.elementAt(i)); Value v = Util.VOID; try { v = r.eval(fun, sargs); if (noRepl) { if (v instanceof Quantity) returnCode = ((Quantity) v).indexValue(); else if (!(v instanceof SchemeVoid)) { System.out.println(v); } } } catch (SchemeException se) { se.printStackTrace(); returnCode = 1; } } } DynamicEnvironment dynenv = r.dynenv; Context.exit(); if (!noRepl) { String listen = (String) args.get("listen"); if (listen != null) { int cidx = listen.indexOf(':'); ServerSocket ssocket = cidx == -1 ? new ServerSocket(Integer.parseInt(listen), 50) : new ServerSocket(Integer.parseInt(listen.substring(cidx + 1)), 50, InetAddress.getByName(listen.substring(0, cidx))); System.out.println("Listening on " + ssocket.getInetAddress().toString() + ":" + ssocket.getLocalPort()); System.out.flush(); listen(ctx, ssocket); } else { REPL repl = new REPL(dynenv, getCliProc(ctx)); repl.go(); repl.primordialThread.thread.join(); switch(repl.primordialThread.state) { case SchemeThread.FINISHED: if (repl.primordialThread.rv instanceof Quantity) { returnCode = ((Quantity) repl.primordialThread.rv).intValue(); } break; case SchemeThread.FINISHED_ABNORMALLY: returnCode = 1; break; } } } else if (returnCode == 0 && !filesLoadedSuccessfully) { returnCode = 1; } System.exit(returnCode); } Code Sample 2: public String excute(String targetUrl, String params, String type) { URL url; HttpURLConnection connection = null; try { url = new URL(targetUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); connection.setRequestProperty("Content-Language", CHAR_SET); connection.setRequestProperty("Connection", "close"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (params != null) { if (params.length() > 0) { DataOutputStream wr; wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); } } InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, CHAR_SET)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append("\r\n"); } rd.close(); return response.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public static String MD5(String text) throws ProducteevSignatureException { try { MessageDigest md; md = MessageDigest.getInstance(ALGORITHM); byte[] md5hash; md.update(text.getBytes("utf-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nsae) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, nsae); } catch (UnsupportedEncodingException e) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, e); } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } } Code Sample 2: public String download(String urlStr) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); System.out.println(buffer); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); }
00
Code Sample 1: @Override public boolean delete(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasDelete = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("delete")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasDelete = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasDelete > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Delete"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } } Code Sample 2: public static String simplePostRequest(String path, Map<String, Object> model) { try { URL url = new URL(path); URLConnection con = url.openConnection(); con.setDoOutput(true); OutputStream out = con.getOutputStream(); OutputStream bout = new BufferedOutputStream(out); OutputStreamWriter writer = new OutputStreamWriter(bout); boolean first = true; for (String name : model.keySet()) { String value = (String) model.get(name); if (!first) { writer.write("&"); first = false; } writer.write(name + "=" + value); } writer.flush(); writer.close(); InputStream stream = new BufferedInputStream(con.getInputStream()); Reader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder buffer = new StringBuilder(); for (int c = reader.read(); c != -1; c = reader.read()) { buffer.append((char) c); } return buffer.toString(); } catch (MalformedURLException e) { throw new CVardbException(e); } catch (IOException e) { throw new CVardbException(e); } }
11
Code Sample 1: public static void copyAFile(final String entree, final String sortie) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(entree).getChannel(); out = new FileOutputStream(sortie).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: private void addMaintainerScripts(TarOutputStream tar, PackageInfo info) throws IOException, ScriptDataTooLargeException { for (final MaintainerScript script : info.getMaintainerScripts().values()) { if (script.getSize() > Integer.MAX_VALUE) { throw new ScriptDataTooLargeException("The script data is too large for the tar file. script=[" + script.getType().getFilename() + "]."); } final TarEntry entry = standardEntry(script.getType().getFilename(), UnixStandardPermissions.EXECUTABLE_FILE_MODE, (int) script.getSize()); tar.putNextEntry(entry); IOUtils.copy(script.getStream(), tar); tar.closeEntry(); } }
11
Code Sample 1: private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), e); } } Code Sample 2: @Override public void objectToEntry(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } }
11
Code Sample 1: private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } } Code Sample 2: @Override public void run() { EventType type = event.getEventType(); IBaseObject field = event.getField(); log.info("select----->" + field.getAttribute(IDatafield.URL)); try { IParent parent = field.getParent(); String name = field.getName(); if (type == EventType.ON_BTN_CLICK) { invoke(parent, "eventRule_" + name); Object value = event.get(Event.ARG_VALUE); if (value != null && value instanceof String[]) { String[] args = (String[]) value; for (String arg : args) log.info("argument data: " + arg); } } else if (type == EventType.ON_BEFORE_DOWNLOAD) invoke(parent, "eventRule_" + name); else if (type == EventType.ON_VALUE_CHANGE) { String pattern = (String) event.get(Event.ARG_PATTERN); Object value = event.get(Event.ARG_VALUE); Class cls = field.getDataType(); if (cls == null || value == null || value.getClass().equals(cls)) field.setValue(value); else if (pattern == null) field.setValue(ConvertUtils.convert(value.toString(), cls)); else if (Date.class.isAssignableFrom(cls)) field.setValue(new SimpleDateFormat(pattern).parse((String) value)); else if (Number.class.isAssignableFrom(cls)) field.setValue(new DecimalFormat(pattern).parse((String) value)); else field.setValue(new MessageFormat(pattern).parse((String) value)); invoke(parent, "checkRule_" + name); invoke(parent, "defaultRule_" + name); } else if (type == EventType.ON_ROW_SELECTED) { log.info("table row selected."); Object selected = event.get(Event.ARG_ROW_INDEX); if (selected instanceof Integer) presentation.setSelectedRowIndex((IModuleList) field, (Integer) selected); else if (selected instanceof List) { String s = ""; String conn = ""; for (Integer item : (List<Integer>) selected) { s = s + conn + item; conn = ","; } log.info("row " + s + " line(s) been selected."); } } else if (type == EventType.ON_ROW_DBLCLICK) { log.info("table row double-clicked."); presentation.setSelectedRowIndex((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_ROW_INSERT) { log.info("table row inserted."); listAdd((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_ROW_REMOVE) { log.info("table row removed."); listRemove((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_FILE_UPLOAD) { log.info("file uploaded."); InputStream is = (InputStream) event.get(Event.ARG_VALUE); String uploadFileName = (String) event.get(Event.ARG_FILE_NAME); log.info("<-----file name:" + uploadFileName); OutputStream os = (OutputStream) field.getValue(); IOUtils.copy(is, os); is.close(); os.close(); } } catch (Exception e) { if (field != null) log.info("field type is :" + field.getDataType().getName()); log.info("select", e); } }
00
Code Sample 1: public void add(final String name, final String content) { forBundle(new BundleManipulator() { public boolean includeEntry(String entryName) { return !name.equals(entryName); } public void finish(Bundle bundle, ZipOutputStream zout) throws IOException { zout.putNextEntry(new ZipEntry(name)); IOUtils.copy(new StringReader(content), zout, "UTF-8"); } }); } Code Sample 2: protected void loadResourceLocations() { try { for (String path : resourceLocations) { if (path.startsWith("${") && path.endsWith("}")) { int start = path.indexOf('{') + 1; int end = path.indexOf('}'); String key = path.substring(start, end).trim(); if (key.equals(ApplicationConstants.RESOURCE_SQL_LOCATION_PROP_NAME)) path = AdminHelper.getRepository().getURI("sql"); else path = AdminHelper.getRepository().getSetupApplicationProperties().get(key); log.debug(key + "=" + path); } FileObject fo = VFSUtils.resolveFile(path); if (fo.exists()) { URL url = fo.getURL(); url.openConnection(); if (fastDeploy) { if (log.isDebugEnabled()) { log.debug("Fast deploy : " + url); AdminSqlQueryFactory builder = null; for (DirectoryListener listener : scanner.getDirectoryListeners()) { if (listener instanceof AdminSqlQueryFactory) { builder = (AdminSqlQueryFactory) listener; } } File file = new File(url.getFile()); fastDeploy(file, builder); } } scanner.addScanURL(url); } } } catch (Exception e) { } }
11
Code Sample 1: private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; } Code Sample 2: public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } }
00
Code Sample 1: private Image getIcon(Element e) { if (!addIconsToButtons) { return null; } else { NodeList nl = e.getElementsByTagName("rc:iconURL"); if (nl.getLength() > 0) { String urlString = nl.item(0).getTextContent(); try { Image img = new Image(Display.getCurrent(), new URL(urlString).openStream()); return img; } catch (Exception exception) { logger.warn("Can't read " + urlString + " using default icon instead."); } } return new Image(Display.getCurrent(), this.getClass().getResourceAsStream("/res/default.png")); } } Code Sample 2: public XmlDocument parseLocation(String locationUrl) { URL url = null; try { url = new URL(locationUrl); } catch (MalformedURLException e) { throw new XmlBuilderException("could not parse URL " + locationUrl, e); } try { return parseInputStream(url.openStream()); } catch (IOException e) { throw new XmlBuilderException("could not open connection to URL " + locationUrl, e); } }
11
Code Sample 1: public static void addImageDB(String pictogramsPath, String pictogramToAddPath, String language, String type, String word) { try { Class.forName("org.sqlite.JDBC"); String fileName = pictogramsPath + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { int idL = 0, idT = 0; G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select id from language where name=\"" + language + "\""); while (rs.next()) { idL = rs.getInt("id"); } rs.close(); stat.close(); stat = G.conn.createStatement(); rs = stat.executeQuery("select id from type where name=\"" + type + "\""); while (rs.next()) { idT = rs.getInt("id"); } rs.close(); stat.close(); String id = pictogramToAddPath.substring(pictogramToAddPath.lastIndexOf(File.separator) + 1, pictogramToAddPath.length()); String idOrig = id; String pathSrc = pictogramToAddPath; String pathDst = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, word.toLowerCase()); stmt.setInt(2, idL); stmt.setInt(3, idT); stmt.setString(4, id); stmt.setString(5, idOrig); stmt.executeUpdate(); stmt.close(); G.conn.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public synchronized List<AnidbSearchResult> getAnimeTitles() throws Exception { URL url = new URL("http", host, "/api/animetitles.dat.gz"); ResultCache cache = getCache(); @SuppressWarnings("unchecked") List<AnidbSearchResult> anime = (List) cache.getSearchResult(null, Locale.ROOT); if (anime != null) { return anime; } Pattern pattern = Pattern.compile("^(?!#)(\\d+)[|](\\d)[|]([\\w-]+)[|](.+)$"); Map<Integer, String> primaryTitleMap = new HashMap<Integer, String>(); Map<Integer, Map<String, String>> officialTitleMap = new HashMap<Integer, Map<String, String>>(); Map<Integer, Map<String, String>> synonymsTitleMap = new HashMap<Integer, Map<String, String>>(); Scanner scanner = new Scanner(new GZIPInputStream(url.openStream()), "UTF-8"); try { while (scanner.hasNextLine()) { Matcher matcher = pattern.matcher(scanner.nextLine()); if (matcher.matches()) { int aid = Integer.parseInt(matcher.group(1)); String type = matcher.group(2); String language = matcher.group(3); String title = matcher.group(4); if (type.equals("1")) { primaryTitleMap.put(aid, title); } else if (type.equals("2") || type.equals("4")) { Map<Integer, Map<String, String>> titleMap = (type.equals("4") ? officialTitleMap : synonymsTitleMap); Map<String, String> languageTitleMap = titleMap.get(aid); if (languageTitleMap == null) { languageTitleMap = new HashMap<String, String>(); titleMap.put(aid, languageTitleMap); } languageTitleMap.put(language, title); } } } } finally { scanner.close(); } anime = new ArrayList<AnidbSearchResult>(primaryTitleMap.size()); for (Entry<Integer, String> entry : primaryTitleMap.entrySet()) { Map<String, String> localizedTitles = new HashMap<String, String>(); if (synonymsTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(synonymsTitleMap.get(entry.getKey())); } if (officialTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(officialTitleMap.get(entry.getKey())); } anime.add(new AnidbSearchResult(entry.getKey(), entry.getValue(), localizedTitles)); } return cache.putSearchResult(null, Locale.ROOT, anime); } Code Sample 2: public List<BoardObject> favBoard() throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_FAV); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response) && HTTPUtil.isXmlContentType(response)) { Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parseFavBoardList(doc); } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
00
Code Sample 1: private void generateDocFile(String srcFileName, String s, String destFileName) { try { ZipFile docxFile = new ZipFile(new File(srcFileName)); ZipEntry documentXML = docxFile.getEntry("word/document.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream documentXMLIS1 = docxFile.getInputStream(documentXML); Document doc = dbf.newDocumentBuilder().parse(documentXMLIS1); Transformer t = TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(baos)); ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(destFileName)); Enumeration<ZipEntry> entriesIter = (Enumeration<ZipEntry>) docxFile.entries(); while (entriesIter.hasMoreElements()) { ZipEntry entry = entriesIter.nextElement(); if (entry.getName().equals("word/document.xml")) { docxOutFile.putNextEntry(new ZipEntry(entry.getName())); byte[] datas = s.getBytes("UTF-8"); docxOutFile.write(datas, 0, datas.length); docxOutFile.closeEntry(); } else if (entry.getName().equals("word/media/image1.png")) { InputStream incoming = new FileInputStream("c:/aaa.jpg"); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } else { InputStream incoming = docxFile.getInputStream(entry); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } } docxOutFile.close(); } catch (Exception e) { } } Code Sample 2: private Bitmap downloadBitmap(String url) { final AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(LOG_TAG, "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (Exception e) { getRequest.abort(); Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e); } finally { if (client != null) { client.close(); } } return null; }
11
Code Sample 1: public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req, ActionResponse res) throws Exception { boolean editor = false; req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, false); User user = _getUser(req); List<Role> roles = RoleFactory.getAllRolesForUser(user.getUserId()); for (Role role : roles) { if (role.getName().equals("Report Administrator") || role.getName().equals("Report Editor") || role.getName().equals("CMS Administrator")) { req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, true); editor = true; break; } } requiresInput = false; badParameters = false; newReport = false; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); String cmd = req.getParameter(Constants.CMD); Logger.debug(this, "Inside EditReportAction cmd=" + cmd); ReportForm rfm = (ReportForm) form; ArrayList<String> ds = (DbConnectionFactory.getAllDataSources()); ArrayList<DataSource> dsResults = new ArrayList<DataSource>(); for (String dataSource : ds) { DataSource d = rfm.getNewDataSource(); if (dataSource.equals(com.dotmarketing.util.Constants.DATABASE_DEFAULT_DATASOURCE)) { d.setDsName("DotCMS Datasource"); } else { d.setDsName(dataSource); } dsResults.add(d); } rfm.setDataSources(dsResults); httpReq.setAttribute("dataSources", rfm.getDataSources()); Long reportId = UtilMethods.parseLong(req.getParameter("reportId"), 0); String referrer = req.getParameter("referrer"); if (reportId > 0) { report = ReportFactory.getReport(reportId); ArrayList<String> adminRoles = new ArrayList<String>(); adminRoles.add(com.dotmarketing.util.Constants.ROLE_REPORT_ADMINISTRATOR); if (user.getUserId().equals(report.getOwner())) { _checkWritePermissions(report, user, httpReq, adminRoles); } if (cmd == null || !cmd.equals(Constants.EDIT)) { rfm.setSelectedDataSource(report.getDs()); rfm.setReportName(report.getReportName()); rfm.setReportDescription(report.getReportDescription()); rfm.setReportId(report.getInode()); rfm.setWebFormReport(report.isWebFormReport()); httpReq.setAttribute("selectedDS", report.getDs()); } } else { if (!editor) { throw new DotRuntimeException("user not allowed to create a new report"); } report = new Report(); report.setOwner(_getUser(req).getUserId()); newReport = true; } req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, report); if ((cmd != null) && cmd.equals(Constants.EDIT)) { if (Validator.validate(req, form, mapping)) { report.setReportName(rfm.getReportName()); report.setReportDescription(rfm.getReportDescription()); report.setWebFormReport(rfm.isWebFormReport()); if (rfm.isWebFormReport()) report.setDs("None"); else report.setDs(rfm.getSelectedDataSource()); String jrxmlPath = ""; String jasperPath = ""; try { HibernateUtil.startTransaction(); ReportFactory.saveReport(report); _applyPermissions(req, report); if (!rfm.isWebFormReport()) { if (UtilMethods.isSet(Config.getStringProperty("ASSET_REAL_PATH"))) { jrxmlPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"; jasperPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"; } else { jrxmlPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"); jasperPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"); } UploadPortletRequest upr = PortalUtil.getUploadPortletRequest(req); File importFile = upr.getFile("jrxmlFile"); if (importFile.exists()) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(importFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); File f = new File(jrxmlPath); FileChannel channelTo = new FileOutputStream(f).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); try { JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath); } catch (Exception e) { Logger.error(this, "Unable to compile or save jrxml: " + e.toString()); try { f = new File(jrxmlPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jrxml. This is usually a permissions problem."); } try { f = new File(jasperPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jasper. This is usually a permissions problem."); } HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", UtilMethods.htmlLineBreak(e.getMessage())); setForward(req, "portlet.ext.report.edit_report"); return; } JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath); ReportParameterFactory.deleteReportsParameters(report); _loadReportParameters(jasperReport.getParameters()); report.setRequiresInput(requiresInput); HibernateUtil.save(report); } else if (newReport) { HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", "message.report.compile.error"); setForward(req, "portlet.ext.report.edit_report"); return; } } HibernateUtil.commitTransaction(); HashMap params = new HashMap(); SessionMessages.add(req, "message", "message.report.upload.success"); params.put("struts_action", new String[] { "/ext/report/view_reports" }); referrer = com.dotmarketing.util.PortletURLUtil.getRenderURL(((ActionRequestImpl) req).getHttpServletRequest(), javax.portlet.WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, referrer); return; } catch (Exception ex) { HibernateUtil.rollbackTransaction(); Logger.error(this, "Unable to save Report: " + ex.toString()); File f; Logger.info(this, "Trying to delete jrxml"); try { f = new File(jrxmlPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jrxml. This is usually because the file doesn't exist."); } try { f = new File(jasperPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jasper. This is usually because the file doesn't exist."); } if (badParameters) { SessionMessages.add(req, "error", ex.getMessage()); } else { SessionMessages.add(req, "error", "message.report.compile.error"); } setForward(req, "portlet.ext.report.edit_report"); return; } } else { setForward(req, "portlet.ext.report.edit_report"); } } if ((cmd != null) && cmd.equals("downloadReportSource")) { ActionResponseImpl resImpl = (ActionResponseImpl) res; HttpServletResponse response = resImpl.getHttpServletResponse(); if (!downloadSourceReport(reportId, httpReq, response)) { SessionMessages.add(req, "error", "message.report.source.file.not.found"); } } setForward(req, "portlet.ext.report.edit_report"); } Code Sample 2: public void launchJob(final String workingDir, final AppConfigType appConfig) throws FaultType { logger.info("called for job: " + jobID); MessageContext mc = MessageContext.getCurrentContext(); HttpServletRequest req = (HttpServletRequest) mc.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); String clientDN = (String) req.getAttribute(GSIConstants.GSI_USER_DN); if (clientDN != null) { logger.info("Client's DN: " + clientDN); } else { clientDN = "Unknown client"; } String remoteIP = req.getRemoteAddr(); SOAPService service = mc.getService(); String serviceName = service.getName(); if (serviceName == null) { serviceName = "Unknown service"; } if (appConfig.isParallel()) { if (AppServiceImpl.drmaaInUse) { if (AppServiceImpl.drmaaPE == null) { logger.error("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); } if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "using DRMAA"); } } else if (!AppServiceImpl.globusInUse) { if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution without using Globus"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "without using Globus"); } } if (jobIn.getNumProcs() == null) { logger.error("Number of processes unspecified for parallel job"); throw new FaultType("Number of processes unspecified for parallel job"); } else if (jobIn.getNumProcs().intValue() > AppServiceImpl.numProcs) { logger.error("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); throw new FaultType("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); } } try { status.setCode(GramJob.STATUS_PENDING); status.setMessage("Launching executable"); status.setBaseURL(new URI(AppServiceImpl.tomcatURL + jobID)); } catch (MalformedURIException mue) { logger.error("Cannot convert base_url string to URI - " + mue.getMessage()); throw new FaultType("Cannot convert base_url string to URI - " + mue.getMessage()); } if (!AppServiceImpl.dbInUse) { AppServiceImpl.statusTable.put(jobID, status); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { logger.error("Cannot connect to database - " + e.getMessage()); throw new FaultType("Cannot connect to database - " + e.getMessage()); } String time = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.US).format(new Date()); String sqlStmt = "insert into job_status(job_id, code, message, base_url, " + "client_dn, client_ip, service_name, start_time, last_update) " + "values ('" + jobID + "', " + status.getCode() + ", " + "'" + status.getMessage() + "', " + "'" + status.getBaseURL() + "', " + "'" + clientDN + "', " + "'" + remoteIP + "', " + "'" + serviceName + "', " + "'" + time + "', " + "'" + time + "');"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); conn.close(); } catch (SQLException e) { logger.error("Cannot insert job status into database - " + e.getMessage()); throw new FaultType("Cannot insert job status into database - " + e.getMessage()); } } String args = appConfig.getDefaultArgs(); if (args == null) { args = jobIn.getArgList(); } else { String userArgs = jobIn.getArgList(); if (userArgs != null) args += " " + userArgs; } if (args != null) { args = args.trim(); } logger.debug("Argument list: " + args); if (AppServiceImpl.drmaaInUse) { String cmd = null; String[] argsArray = null; if (appConfig.isParallel()) { cmd = "/bin/sh"; String newArgs = AppServiceImpl.mpiRun + " -machinefile $TMPDIR/machines" + " -np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation(); if (args != null) { args = newArgs + " " + args; } else { args = newArgs; } logger.debug("CMD: " + args); argsArray = new String[] { "-c", args }; } else { cmd = appConfig.getBinaryLocation(); if (args == null) args = ""; logger.debug("CMD: " + cmd + " " + args); argsArray = args.split(" "); } try { logger.debug("Working directory: " + workingDir); JobTemplate jt = session.createJobTemplate(); if (appConfig.isParallel()) jt.setNativeSpecification("-pe " + AppServiceImpl.drmaaPE + " " + jobIn.getNumProcs()); jt.setRemoteCommand(cmd); jt.setArgs(argsArray); jt.setJobName(jobID); jt.setWorkingDirectory(workingDir); jt.setErrorPath(":" + workingDir + "/stderr.txt"); jt.setOutputPath(":" + workingDir + "/stdout.txt"); drmaaJobID = session.runJob(jt); logger.info("DRMAA job has been submitted with id " + drmaaJobID); session.deleteJobTemplate(jt); } catch (Exception ex) { logger.error(ex); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via DRMAA - " + ex.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } else if (AppServiceImpl.globusInUse) { String rsl = null; if (appConfig.isParallel()) { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(count=" + jobIn.getNumProcs() + ")" + "(jobtype=mpi)" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } else { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } if (args != null) { args = "\"" + args + "\""; args = args.replaceAll("[\\s]+", "\" \""); rsl += "(arguments=" + args + ")"; } logger.debug("RSL: " + rsl); try { job = new GramJob(rsl); GlobusCredential globusCred = new GlobusCredential(AppServiceImpl.serviceCertPath, AppServiceImpl.serviceKeyPath); GSSCredential gssCred = new GlobusGSSCredentialImpl(globusCred, GSSCredential.INITIATE_AND_ACCEPT); job.setCredentials(gssCred); job.addListener(this); job.request(AppServiceImpl.gatekeeperContact); } catch (Exception ge) { logger.error(ge); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via Globus - " + ge.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } } else { String cmd = null; if (appConfig.isParallel()) { cmd = new String(AppServiceImpl.mpiRun + " " + "-np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation()); } else { cmd = new String(appConfig.getBinaryLocation()); } if (args != null) { cmd += " " + args; } logger.debug("CMD: " + cmd); try { logger.debug("Working directory: " + workingDir); proc = Runtime.getRuntime().exec(cmd, null, new File(workingDir)); stdoutThread = writeStdOut(proc, workingDir); stderrThread = writeStdErr(proc, workingDir); } catch (IOException ioe) { logger.error(ioe); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via fork - " + ioe.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } new Thread() { public void run() { try { waitForCompletion(); } catch (FaultType f) { logger.error(f); synchronized (status) { status.notifyAll(); } return; } if (AppServiceImpl.drmaaInUse || !AppServiceImpl.globusInUse) { done = true; status.setCode(GramJob.STATUS_STAGE_OUT); status.setMessage("Writing output metadata"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } } try { if (!AppServiceImpl.drmaaInUse && !AppServiceImpl.globusInUse) { try { logger.debug("Waiting for all outputs to be written out"); stdoutThread.join(); stderrThread.join(); logger.debug("All outputs successfully written out"); } catch (InterruptedException ignore) { } } File stdOutFile = new File(workingDir + File.separator + "stdout.txt"); if (!stdOutFile.exists()) { throw new IOException("Standard output missing for execution"); } File stdErrFile = new File(workingDir + File.separator + "stderr.txt"); if (!stdErrFile.exists()) { throw new IOException("Standard error missing for execution"); } if (AppServiceImpl.archiveData) { logger.debug("Archiving output files"); File f = new File(workingDir); File[] outputFiles = f.listFiles(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(workingDir + File.separator + jobID + ".zip")); byte[] buf = new byte[1024]; try { for (int i = 0; i < outputFiles.length; i++) { FileInputStream in = new FileInputStream(outputFiles[i]); out.putNextEntry(new ZipEntry(outputFiles[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { logger.error(e); logger.error("Error not fatal - moving on"); } } File f = new File(workingDir); File[] outputFiles = f.listFiles(); OutputFileType[] outputFileObj = new OutputFileType[outputFiles.length - 2]; int j = 0; for (int i = 0; i < outputFiles.length; i++) { if (outputFiles[i].getName().equals("stdout.txt")) { outputs.setStdOut(new URI(AppServiceImpl.tomcatURL + jobID + "/stdout.txt")); } else if (outputFiles[i].getName().equals("stderr.txt")) { outputs.setStdErr(new URI(AppServiceImpl.tomcatURL + jobID + "/stderr.txt")); } else { OutputFileType next = new OutputFileType(); next.setName(outputFiles[i].getName()); next.setUrl(new URI(AppServiceImpl.tomcatURL + jobID + "/" + outputFiles[i].getName())); outputFileObj[j++] = next; } } outputs.setOutputFile(outputFileObj); } catch (IOException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot retrieve outputs after finish - " + e.getMessage()); logger.error(e); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } } synchronized (status) { status.notifyAll(); } return; } if (!AppServiceImpl.dbInUse) { AppServiceImpl.outputTable.put(jobID, outputs); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot connect to database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } String sqlStmt = "insert into job_output(job_id, std_out, std_err) " + "values ('" + jobID + "', " + "'" + outputs.getStdOut().toString() + "', " + "'" + outputs.getStdErr().toString() + "');"; Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update job output database after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } OutputFileType[] outputFile = outputs.getOutputFile(); for (int i = 0; i < outputFile.length; i++) { sqlStmt = "insert into output_file(job_id, name, url) " + "values ('" + jobID + "', " + "'" + outputFile[i].getName() + "', " + "'" + outputFile[i].getUrl().toString() + "');"; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update output_file DB after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } } } if (terminatedOK()) { status.setCode(GramJob.STATUS_DONE); status.setMessage("Execution complete - " + "check outputs to verify successful execution"); } else { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Execution failed"); } if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } AppServiceImpl.jobTable.remove(jobID); synchronized (status) { status.notifyAll(); } logger.info("Execution complete for job: " + jobID); } }.start(); }
11
Code Sample 1: private void execute(File file) throws IOException { if (file == null) throw new RuntimeException("undefined file"); if (!file.exists()) throw new RuntimeException("file not found :" + file); if (!file.isFile()) throw new RuntimeException("not a file :" + file); String login = cfg.getProperty(GC_USERNAME); String password = null; if (cfg.containsKey(GC_PASSWORD)) { password = cfg.getProperty(GC_PASSWORD); } else { password = new String(Base64.decode(cfg.getProperty(GC_PASSWORD64))); } PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(login + ":" + password)); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new IOException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: public MemoryBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
11
Code Sample 1: public void handleRequestInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { final String servetPath = httpServletRequest.getServletPath(); final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH); final String currentToken = getETagValue(httpServletRequest); httpServletResponse.setHeader(ETAG, currentToken); final Date modifiedDate = new Date(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE)); final Calendar calendar = Calendar.getInstance(); final Date now = calendar.getTime(); calendar.setTime(modifiedDate); calendar.add(Calendar.MINUTE, getEtagExpiration()); if (currentToken.equals(previousToken) && (now.getTime() < calendar.getTime().getTime())) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED); httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE)); if (LOG.isDebugEnabled()) { LOG.debug("ETag the same, will return 304"); } } else { httpServletResponse.setDateHeader(LAST_MODIFIED, (new Date()).getTime()); final String width = httpServletRequest.getParameter(Constants.WIDTH); final String height = httpServletRequest.getParameter(Constants.HEIGHT); final ImageNameStrategy imageNameStrategy = imageService.getImageNameStrategy(servetPath); String code = imageNameStrategy.getCode(servetPath); String fileName = imageNameStrategy.getFileName(servetPath); final String imageRealPathPrefix = getRealPathPrefix(httpServletRequest.getServerName().toLowerCase()); String original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); final File origFile = new File(original); if (!origFile.exists()) { code = Constants.NO_IMAGE; fileName = imageNameStrategy.getFileName(code); original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); } String resizedImageFileName = null; if (width != null && height != null && imageService.isSizeAllowed(width, height)) { resizedImageFileName = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code, width, height); } final File imageFile = getImageFile(original, resizedImageFileName, width, height); final FileInputStream fileInputStream = new FileInputStream(imageFile); IOUtils.copy(fileInputStream, httpServletResponse.getOutputStream()); fileInputStream.close(); } } Code Sample 2: @HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
00
Code Sample 1: @Override protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws IOException, ClassNotFoundException { HttpPost postMethod = new HttpPost(config.getServiceUrl()); postMethod.setEntity(new ByteArrayEntity(baos.toByteArray())); HttpResponse rsp = httpClient.execute(postMethod); StatusLine sl = rsp.getStatusLine(); if (sl.getStatusCode() >= 300) { throw new IOException("Did not receive successful HTTP response: status code = " + sl.getStatusCode() + ", status message = [" + sl.getReasonPhrase() + "]"); } HttpEntity entity = rsp.getEntity(); InputStream responseBody = entity.getContent(); return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); } Code Sample 2: private void transferir() { PreparedStatement ps = null; StringBuilder sql = new StringBuilder(); boolean problema = false; String idFk = ""; try { for (String tabela : tabelas) { idFk = mapaTabelas.get(tabela); sql.delete(0, sql.length()); sql.append("UPDATE "); sql.append(tabela); sql.append(" SET"); sql.append(" CODEMP" + idFk + "=?,"); sql.append(" CODFILIAL" + idFk + "=?,"); sql.append(" CODPLAN=?"); sql.append(" WHERE"); sql.append(" CODEMP" + idFk + "=? AND"); sql.append(" CODFILIAL" + idFk + "=? AND"); sql.append(" CODPLAN=?"); try { status.setText("Atulizando tabela " + tabela); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, lcPlanDest.getCodFilial()); ps.setString(3, txtCodPlanDest.getVlrString()); ps.setInt(4, Aplicativo.iCodEmp); ps.setInt(5, lcPlanOrig.getCodFilial()); ps.setString(6, txtCodPlanOrig.getVlrString()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); problema = true; Funcoes.mensagemErro(this, "Erro ao atualizar planejamento de destino.\n" + e.getMessage(), true, con, e); status.setText(""); break; } } } finally { try { if (problema) { con.rollback(); } else { sql.delete(0, sql.length()); sql.append("DELETE FROM FNSALDOLANCA "); sql.append("WHERE CODEMPPN=? AND CODFILIALPN=? AND CODPLAN=?"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, lcPlanOrig.getCodFilial()); ps.setString(3, txtCodPlanOrig.getVlrString()); ps.executeUpdate(); con.commit(); btTransferir.setEnabled(false); status.setText("Transfer�ncia completada."); } } catch (SQLException e) { e.printStackTrace(); } } }
11
Code Sample 1: public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Key key = null; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey)); key = (Key) in.readObject(); } catch (IOException ioe) { KeyGenerator generator = KeyGenerator.getInstance(algorithm); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey)); out.writeObject(key); out.close(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm)); FileInputStream in = new FileInputStream(plain); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher); byte[] buffer = new byte[4096]; for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.close(); } Code Sample 2: private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
00
Code Sample 1: public static Vector<String> readFileFromURL(URL url) { Vector<String> text = new Vector<String>(); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { text.add(line); } in.close(); } catch (Exception e) { return null; } return text; } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
00
Code Sample 1: @Override protected URLConnection openConnection(URL url) throws IOException { final String urlPath = url.getPath(); final int status; final String path; String statusAsString = extractValue(urlPath, STATUS_REGEX, STATUS_CAPTURE); status = statusAsString == null ? 200 : Integer.parseInt(statusAsString); path = extractPath(urlPath); if (saved.get(url.toString()) == null) { saved.put(url.toString(), new ArrayList<ByteArrayOutputStream>()); } return new HttpsURLConnection(url) { @Override public int getResponseCode() throws IOException { return status; } @Override public InputStream getInputStream() throws IOException { if (errorStatus()) throw new IOException("fake server returned a fake error"); if (path == null) { return new ByteArrayInputStream(new byte[0]); } else { return new FileInputStream(path); } } @Override public InputStream getErrorStream() { if (errorStatus()) { try { return new FileInputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } else { return null; } } @Override public OutputStream getOutputStream() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); Handler.saved.get(url.toString()).add(out); return out; } @Override public String getContentType() { return "test/plain"; } @Override public void connect() throws IOException { } @Override public boolean usingProxy() { return false; } @Override public void disconnect() { } private boolean errorStatus() { return status >= 500 && status <= 599; } @Override public String getCipherSuite() { return null; } @Override public Certificate[] getLocalCertificates() { return null; } @Override public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException { return null; } }; } Code Sample 2: public static BufferedReader getReader(int license) { URL url = getResource(license); if (url == null) return null; InputStream inStream; try { inStream = url.openStream(); } catch (IOException e) { return null; } return new BufferedReader(new InputStreamReader(inStream)); }
11
Code Sample 1: @RequestMapping(value = "/verdocumentoFisico.html", method = RequestMethod.GET) public String editFile(ModelMap model, @RequestParam("id") int idAnexo) { Anexo anexo = anexoService.selectById(idAnexo); model.addAttribute("path", anexo.getAnexoCaminho()); try { InputStream is = new FileInputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); IOUtils.copy(is, fos); Runtime.getRuntime().exec("chmod 777 " + config.tempDir + anexo.getAnexoCaminho()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "verdocumentoFisico"; } Code Sample 2: private void copyFile(URL from, File to) { try { InputStream is = from.openStream(); IOUtils.copy(is, new FileOutputStream(to)); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: private void analyseCorpus(final IStatusDisplayer fStatus) { final String sDistrosFile = "Distros.tmp"; final String sSymbolsFile = "Symbols.tmp"; Chunker = new EntropyChunker(); int Levels = 2; sgOverallGraph = new SymbolicGraph(1, Levels); siIndex = new SemanticIndex(sgOverallGraph); try { siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor(); } catch (IOException ioe) { siIndex.MeaningExtractor = null; } try { DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0); dsSet.createSets(true, (double) 100 / 100); int iCurCnt, iTotal; String sFile = ""; Iterator iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } appendToLog("Training chunker..."); Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET)); appendToLog("Setting delimiters..."); setDelimiters(Chunker.getDelimiters()); iCurCnt = 0; cdDoc = new DistributionDocument[Levels]; for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt); fStatus.setVisible(true); ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1); appendToLog("(Pass 1/3) Loading files..." + sFile); TreeSet tsOverallSymbols = new TreeSet(); while (iIter.hasNext()) { sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal); final DistributionDocument[] cdDocArg = cdDoc; final String sFileArg = sFile; for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) { final int iCntArg = iCnt; while (!t.addThreadFor(new Runnable() { public void run() { if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else { cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false); } } })) Thread.yield(); } try { t.waitUntilCompletion(); } catch (InterruptedException ex) { ex.printStackTrace(System.err); appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString()); sgOverallGraph.loadFromFile(sFile); fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal); Thread.yield(); } Set sSymbols = null; File fPreviousSymbols = new File(sSymbolsFile); boolean bSymbolsLoadedOK = false; if (fPreviousSymbols.exists()) { System.err.println("ATTENTION: Using previous symbols..."); try { FileInputStream fis = new FileInputStream(fPreviousSymbols); ObjectInputStream ois = new ObjectInputStream(fis); sSymbols = (Set) ois.readObject(); ois.close(); bSymbolsLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); } } if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus); int iMinSymbolSize = Integer.MAX_VALUE; int iMaxSymbolSize = Integer.MIN_VALUE; Iterator iSymbol = sSymbols.iterator(); while (iSymbol.hasNext()) { String sCurSymbol = (String) iSymbol.next(); if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length(); if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length(); } try { FileOutputStream fos = new FileOutputStream(sSymbolsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(sSymbols); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } appendToLog("(Pass 2/3) Determining symbol distros per n-gram size..."); iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } iCurCnt = 0; Distribution dSymbolsPerSize = new Distribution(); Distribution dNonSymbolsPerSize = new Distribution(); Distribution dSymbolSizes = new Distribution(); File fPreviousRun = new File(sDistrosFile); boolean bDistrosLoadedOK = false; if (fPreviousRun.exists()) { System.err.println("ATTENTION: Using previous distros..."); try { FileInputStream fis = new FileInputStream(fPreviousRun); ObjectInputStream ois = new ObjectInputStream(fis); dSymbolsPerSize = (Distribution) ois.readObject(); dNonSymbolsPerSize = (Distribution) ois.readObject(); dSymbolSizes = (Distribution) ois.readObject(); ois.close(); bDistrosLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } } if (!bDistrosLoadedOK) while (iIter.hasNext()) { fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal); sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); String sDataString = ""; try { ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); FileInputStream fiIn = new FileInputStream(sFile); int iData = 0; while ((iData = fiIn.read()) > -1) bsOut.write(iData); sDataString = bsOut.toString(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } final Distribution dSymbolsPerSizeArg = dSymbolsPerSize; final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize; final Distribution dSymbolSizesArg = dSymbolSizes; final String sDataStringArg = sDataString; final Set sSymbolsArg = sSymbols; for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) { final int iSymbolSizeArg = iSymbolSize; while (!t.addThreadFor(new Runnable() { public void run() { NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg); ndCur.setDataString(sDataStringArg); int iSymbolCnt = 0; int iNonSymbolCnt = 0; Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator(); while (iExtracted.hasNext()) { String sCur = ((Vertex) iExtracted.next()).toString(); if (sSymbolsArg.contains(sCur)) { iSymbolCnt++; synchronized (dSymbolSizesArg) { dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0); } } else iNonSymbolCnt++; } synchronized (dSymbolsPerSizeArg) { dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt); } synchronized (dNonSymbolsPerSizeArg) { dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt); } } })) Thread.yield(); } } if (!bDistrosLoadedOK) try { t.waitUntilCompletion(); try { FileOutputStream fos = new FileOutputStream(sDistrosFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(dSymbolsPerSize); oos.writeObject(dNonSymbolsPerSize); oos.writeObject(dSymbolSizes); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } } catch (InterruptedException ex) { appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n"); NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize); IntegerPair p = nseEstimator.getOptimalRange(); appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second()); fStatus.setStatus("Determining optimal distance...", 0.0); DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator); int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second()); fStatus.setStatus("Determining optimal distance...", 1.0); appendToLog("\nOptimal distance:" + iBestDist); appendToLog("======DONE=====\n"); } finally { sgOverallGraph.removeNotificationListener(); } } Code Sample 2: public int extract() throws Exception { int count = 0; if (VERBOSE) System.out.println("IAAE:Extractr.extract: getting ready to extract " + getArtDir().toString()); ITCFileFilter iff = new ITCFileFilter(); RecursiveFileIterator rfi = new RecursiveFileIterator(getArtDir(), iff); FileTypeDeterminer ftd = new FileTypeDeterminer(); File artFile = null; File targetFile = null; broadcastStart(); while (rfi.hasMoreElements()) { artFile = (File) rfi.nextElement(); targetFile = getTargetFile(artFile); if (VERBOSE) System.out.println("IAAE:Extractr.extract: working ont " + artFile.toString()); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream((new FileInputStream(artFile))); out = new BufferedOutputStream((new FileOutputStream(targetFile))); byte[] buffer = new byte[10240]; int read = 0; int total = 0; read = in.read(buffer); while (read != -1) { if ((total <= 491) && (read > 491)) { out.write(buffer, 492, (read - 492)); } else if ((total <= 491) && (read <= 491)) { } else { out.write(buffer, 0, read); } total = total + read; read = in.read(buffer); } } catch (Exception e) { e.printStackTrace(); broadcastFail(); } finally { in.close(); out.close(); } broadcastSuccess(); count++; } broadcastDone(); return count; }
00
Code Sample 1: @Test public void testDocumentDownloadExcel() throws IOException { if (uploadedExcelDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateXlDownloadLink(uploadedExcelDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } } Code Sample 2: private void handleInterfaceDown(long eventID, long nodeID, String ipAddr, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1 || ipAddr == null) { log.warn(EventConstants.INTERFACE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid/ip: " + eventID + "/" + nodeID + "/" + ipAddr); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_INTERFACE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleInterfaceDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); activeSvcsStmt.setString(2, ipAddr); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { long serviceID = activeSvcsRS.getLong(1); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleInterfaceDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleInterfaceDown: Recording new outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID + "/" + ipAddr); } catch (SQLException se) { log.warn("Rolling back transaction, interfaceDown could not be recorded for nodeid/ipAddr: " + nodeID + "/" + ipAddr, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'interfaceDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: private void copyTemplates(ProjectPath pPath) { String sourceAntPath = pPath.sourceAntPath(); final String moduleName = projectOperations.getFocusedTopLevelPackage().toString(); logger.info("Module Name: " + moduleName); String targetDirectory = pPath.canonicalFileSystemPath(projectOperations); logger.info("Moving into target Directory: " + targetDirectory); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } System.out.println("Target Directory: " + pPath.sourceAntPath()); String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); if (urls.isEmpty()) { logger.info("URLS are empty stopping..."); } for (URL url : urls) { logger.info("Stepping into " + url.toExternalForm()); String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); String targetFilename = targetDirectory + fileName; logger.info("Handling " + targetFilename); if (!fileManager.exists(targetFilename)) { try { logger.info("Copied file"); String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage()); logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations)); String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString(); input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage); input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage()); input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName()); input = input.replace("__ENTITY_NAME__", entityName); MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } } Code Sample 2: public static void copyFile(String from, String to, boolean append) throws IOException { FileChannel in = new FileInputStream(from).getChannel(); FileChannel out = new FileOutputStream(to, append).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(BSIZE); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } }
00
Code Sample 1: public boolean addSiteScore(ArrayList<InitScoreTable> siteScores, InitScoreTable scoreTable, String filePath, String strTime) { boolean bResult = false; String strSql = ""; Connection conn = null; Statement stm = null; try { conn = db.getConnection(); conn.setAutoCommit(false); stm = conn.createStatement(); strSql = "delete from t_siteScore where strTaskId = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); for (int i = 0; i < siteScores.size(); i++) { InitScoreTable temp = siteScores.get(i); String tempSql = "select * from t_tagConf where strTagName='" + temp.getStrSiteScoreTagName() + "' and strTagYear='" + temp.getStrSiteScoreYear() + "' "; System.out.println(tempSql); ResultSet rst = stm.executeQuery(tempSql); if (rst.next()) { temp.setStrSiteScoreTagId(rst.getString("strId")); temp.setStrSiteinfoScoreParentId(rst.getString("strParentId")); } rst = null; } Iterator<InitScoreTable> it = siteScores.iterator(); String strCreatedTime = com.siteeval.common.Format.getDateTime(); String taskId = ""; while (it.hasNext()) { InitScoreTable thebean = it.next(); taskId = thebean.getStrSiteScoreTaskId(); String strId = UID.getID(); strSql = "INSERT INTO " + strTableName3 + "(strId,strTaskId,strTagId," + "strTagType,strTagName,strParentId,flaTagScore,strYear,datCreatedTime,strCreator) " + "VALUES('" + strId + "','" + taskId + "','" + thebean.getStrSiteScoreTagId() + "','" + thebean.getStrSiteScoreTagType() + "','" + thebean.getStrSiteScoreTagName() + "','" + thebean.getStrSiteinfoScoreParentId() + "','" + thebean.getFlaSiteScoreTagScore() + "','" + thebean.getStrSiteScoreYear() + "','" + strCreatedTime + "','" + thebean.getStrSiteScoreCreator() + "')"; stm.executeUpdate(strSql); } strSql = "update t_siteTotalScore set strSiteState=1,flaSiteScore='" + scoreTable.getFlaSiteScore() + "',flaInfoDisclosureScore='" + scoreTable.getFlaInfoDisclosureScore() + "',flaOnlineServicesScore='" + scoreTable.getFlaOnlineServicesScore() + "',flaPublicParticipationSore='" + scoreTable.getFlaPublicParticipationSore() + "',flaWebDesignScore='" + scoreTable.getFlaWebDesignScore() + "',strSiteFeature='" + scoreTable.getStrTotalScoreSiteFeature() + "',strSiteAdvantage='" + scoreTable.getStrTotalScoreSiteAdvantage() + "',strSiteFailure='" + scoreTable.getStrTotalScoreSiteFailure() + "' where strTaskId='" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); strSql = "update " + strTableName1 + " set templateUrl='" + filePath + "',dTaskBeginTime='" + strTime + "',dTaskEndTime='" + strTime + "' where strid = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); conn.commit(); bResult = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception eee) { } System.out.println("������վ���ֱ���Ϣʱ���?"); } finally { try { conn.setAutoCommit(true); if (stm != null) { stm.close(); } if (conn != null) { conn.close(); } } catch (Exception ee) { } } return bResult; } Code Sample 2: public static String getUserPass(String user) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(user.getBytes()); byte[] hash = digest.digest(); System.out.println("Returning user pass:" + hash); return hash.toString(); }
00
Code Sample 1: private String MD5Sum(String input) { String hashtext = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } Code Sample 2: @Override public final boolean exists() { try { final URLConnection uc = this.url.openConnection(); uc.connect(); uc.getInputStream().close(); return true; } catch (final IOException e) { return false; } }
11
Code Sample 1: public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); } Code Sample 2: public File convert(URI uri) throws DjatokaException { processing.add(uri.toString()); File urlLocal = null; try { logger.info("processingRemoteURI: " + uri.toURL()); boolean isJp2 = false; InputStream src = IOUtils.getInputStream(uri.toURL()); String ext = uri.toURL().toString().substring(uri.toURL().toString().lastIndexOf(".") + 1).toLowerCase(); if (ext.equals(FORMAT_ID_TIF) || ext.equals(FORMAT_ID_TIFF)) { urlLocal = File.createTempFile("convert" + uri.hashCode(), "." + FORMAT_ID_TIF); } else if (formatMap.containsKey(ext) && (formatMap.get(ext).equals(FORMAT_MIMEYPE_JP2) || formatMap.get(ext).equals(FORMAT_MIMEYPE_JPX))) { urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + ext); isJp2 = true; } else { if (src.markSupported()) src.mark(15); if (ImageProcessingUtils.checkIfJp2(src)) urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + FORMAT_ID_JP2); if (src.markSupported()) src.reset(); else { src.close(); src = IOUtils.getInputStream(uri.toURL()); } } if (urlLocal == null) { urlLocal = File.createTempFile("convert" + uri.hashCode(), ".img"); } urlLocal.deleteOnExit(); FileOutputStream dest = new FileOutputStream(urlLocal); IOUtils.copyStream(src, dest); if (!isJp2) urlLocal = processImage(urlLocal, uri); src.close(); dest.close(); return urlLocal; } catch (Exception e) { urlLocal.delete(); throw new DjatokaException(e); } finally { if (processing.contains(uri.toString())) processing.remove(uri.toString()); } }
11
Code Sample 1: public synchronized String encrypt(String plaintext) throws ServiceRuntimeException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceRuntimeException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceRuntimeException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static String calcolaMd5(String messaggio) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); md.update(messaggio.getBytes()); byte[] impronta = md.digest(); return new String(impronta); }
00
Code Sample 1: public static void copyFile(File src, File dest, boolean force) throws IOException, InterruptedIOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file!"); } } byte[] buffer = new byte[5 * 1024 * 1024]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dest)); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { buffer = null; if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } Code Sample 2: @Override public void run() { try { jButton1.setEnabled(false); jButton2.setEnabled(false); URL url = new URL(updatePath + "currentVersion.txt"); URLConnection con = url.openConnection(); con.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; for (int i = 0; (line = in.readLine()) != null; i++) { URL fileUrl = new URL(updatePath + line); URLConnection filecon = fileUrl.openConnection(); InputStream stream = fileUrl.openStream(); int oneChar, count = 0; int size = filecon.getContentLength(); jProgressBar1.setMaximum(size); jProgressBar1.setValue(0); File testFile = new File(line); String build = ""; for (String dirtest : line.split("/")) { build += dirtest; if (!build.contains(".")) { File dirfile = new File(build); if (!dirfile.exists()) { dirfile.mkdir(); } } build += "/"; } if (testFile.length() == size) { } else { transferFile(line, fileUrl, size); if (line.endsWith("documents.zip")) { ZipInputStream in2 = new ZipInputStream(new FileInputStream(line)); ZipEntry entry; String pathDoc = line.split("documents.zip")[0]; File docDir = new File(pathDoc + "documents"); if (!docDir.exists()) { docDir.mkdir(); } while ((entry = in2.getNextEntry()) != null) { String outFilename = pathDoc + "documents/" + entry.getName(); OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } in2.close(); } if (line.endsWith("mysql.zip")) { ZipFile zipfile = new ZipFile(line); Enumeration entries = zipfile.entries(); String pathDoc = line.split("mysql.zip")[0]; File docDir = new File(pathDoc + "mysql"); if (!docDir.exists()) { docDir.mkdir(); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(pathDoc + "mysql/" + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); InputStream in2 = zipfile.getInputStream(entry); OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName())); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } in2.close(); out.close(); } } } jProgressBar2.setValue(i + 1); labelFileProgress.setText((i + 1) + "/" + numberFiles); } labelStatus.setText("Update Finished"); jButton1.setVisible(false); jButton2.setText("Finished"); jButton1.setEnabled(true); jButton2.setEnabled(true); } catch (IOException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } }
11
Code Sample 1: public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); } Code Sample 2: public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } } } }
00
Code Sample 1: public PVBrowserSearchDocument(URL url, PVBrowserModel applicationModel) { this(applicationModel); if (url != null) { try { data.loadFromXML(url.openStream()); loadOpenPVsFromData(); setHasChanges(false); setSource(url); } catch (java.io.IOException exception) { System.err.println(exception); displayWarning("Open Failed!", exception.getMessage(), exception); } } } Code Sample 2: protected BufferedImage handleNLIBException() { if (params.uri.startsWith("http://digar.nlib.ee/otsing/") || params.uri.startsWith("http://digar.nlib.ee/show")) try { String url = "http://digar.nlib.ee/gmap/nd" + params.uri.substring(params.uri.indexOf(":") + 1, params.uri.lastIndexOf("&")) + "-tiles/z0x0y0.jpeg"; URLConnection connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e) { try { if (params.uri.startsWith("http://digar.nlib.ee/show")) params.uri = "http://digar.nlib.ee/otsing/?pid=" + params.uri.substring(params.uri.lastIndexOf("/") + 1) + "&show"; URLConnection connection = new URL(params.uri).openConnection(); String url = params.uri; if (url.endsWith("&show")) url = url.substring(0, url.length() - 5); int index = url.lastIndexOf("?"); url = "stream" + url.substring(index); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String aux = null; while ((aux = reader.readLine()) != null) { index = aux.indexOf(url); if (index != -1) { url = "http://digar.nlib.ee/otsing/" + aux.substring(index); index = url.indexOf('>'); if (index == -1) index = url.indexOf("\""); url = url.substring(0, index); break; } } connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e2) { } } return null; }
11
Code Sample 1: 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 HashSet<String> href(String urlstr) throws IOException { HashSet<String> hrefs = new HashSet<String>(); URL url = new URL(urlstr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", "_session_id=" + _session_id); InputStreamReader r = new InputStreamReader(con.getInputStream()); StringWriter b = new StringWriter(); IOUtils.copyTo(r, b); r.close(); try { Thread.sleep(WAIT_SECONDS * 1000); } catch (Exception err) { } String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]"); for (String s1 : tokens) { if (!(s1.startsWith("a") && s1.contains("href"))) continue; String tokens2[] = s1.split("[\\\"\\\']"); for (String s2 : tokens2) { if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue; hrefs.add(s2); } } return hrefs; }
00
Code Sample 1: protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } } Code Sample 2: private String getData(String method, String arg) { try { URL url; String str; StringBuilder strBuilder; BufferedReader stream; url = new URL(API_BASE_URL + "/2.1/" + method + "/en/xml/" + API_KEY + "/" + URLEncoder.encode(arg, "UTF-8")); stream = new BufferedReader(new InputStreamReader(url.openStream())); strBuilder = new StringBuilder(); while ((str = stream.readLine()) != null) { strBuilder.append(str); } stream.close(); return strBuilder.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void trimAndWriteNewSff(OutputStream out) throws IOException { TrimParser trimmer = new TrimParser(); SffParser.parseSFF(untrimmedSffFile, trimmer); tempOut.close(); headerBuilder.withNoIndex().numberOfReads(numberOfTrimmedReads); SffWriter.writeCommonHeader(headerBuilder.build(), out); InputStream in = null; try { in = new FileInputStream(tempReadDataFile); IOUtils.copyLarge(in, out); } finally { IOUtil.closeAndIgnoreErrors(in); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public IUserProfile getUserProfile(String profileID) throws MM4UUserProfileNotFoundException { SimpleUserProfile tempProfile = null; String tempProfileString = this.profileURI + profileID + FILE_SUFFIX; try { URL url = new URL(tempProfileString); Debug.println("Retrieve profile with ID: " + url); tempProfile = new SimpleUserProfile(); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String tempLine = null; tempProfile.add("id", profileID); while ((tempLine = input.readLine()) != null) { Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine); if (tempProperty != null) { tempProfile.addIfNotNull(tempProperty.getKey(), tempProperty.getValue()); } } input.close(); } catch (MalformedURLException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } catch (IOException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } return tempProfile; }
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: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void service(Request req, Response resp) { PrintStream out = null; try { out = resp.getPrintStream(8192); String env = req.getParameter("env"); String regex = req.getParameter("regex"); String deep = req.getParameter("deep"); String term = req.getParameter("term"); String index = req.getParameter("index"); String refresh = req.getParameter("refresh"); String searcher = req.getParameter("searcher"); String grep = req.getParameter("grep"); String fiServerDetails = req.getParameter("fi_server_details"); String serverDetails = req.getParameter("server_details"); String hostDetails = req.getParameter("host_details"); String name = req.getParameter("name"); String show = req.getParameter("show"); String path = req.getPath().getPath(); int page = req.getForm().getInteger("page"); if (path.startsWith("/fs")) { String fsPath = path.replaceAll("^/fs", ""); File realPath = new File("C:\\", fsPath.replace('/', File.separatorChar)); if (realPath.isDirectory()) { out.write(FileSystemDirectory.getContents(new File("c:\\"), fsPath, "/fs")); } else { resp.set("Cache", "no-cache"); FileInputStream fin = new FileInputStream(realPath); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Serving " + path + " as " + realPath.getCanonicalPath()); } } else if (path.startsWith("/files/")) { String[] segments = req.getPath().getSegments(); boolean done = false; if (segments.length > 1) { String realPath = req.getPath().getPath(1); File file = context.getFile(realPath); if (file.isFile()) { resp.set("Content-Type", context.getContentType(realPath)); FileInputStream fin = new FileInputStream(file); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); long start = System.currentTimeMillis(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Time take to write [" + realPath + "] was [" + (System.currentTimeMillis() - start) + "] of size [" + file.length() + "]"); done = true; } } if (!done) { resp.set("Content-Type", "text/plain"); out.println("Can not serve directory: path"); } } else if (path.startsWith("/upload")) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); RequestAdapter adapter = new RequestAdapter(req); List<FileItem> list = upload.parseRequest(adapter); Map<String, FileItem> map = new HashMap<String, FileItem>(); for (FileItem entry : list) { String fileName = entry.getFieldName(); map.put(fileName, entry); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body>"); for (int i = 0; i < 10; i++) { Part file = req.getPart("datafile" + (i + 1)); if (file != null && file.isFile()) { String partName = file.getName(); String partFileName = file.getFileName(); File partFile = new File(partFileName); FileItem item = map.get(partName); InputStream in = file.getInputStream(); String fileName = file.getFileName().replaceAll("\\\\", "_").replaceAll(":", "_"); File filePath = new File(fileName); OutputStream fileOut = new FileOutputStream(filePath); byte[] chunk = new byte[8192]; int count = 0; while ((count = in.read(chunk)) != -1) { fileOut.write(chunk, 0, count); } fileOut.close(); in.close(); out.println("<table border='1'>"); out.println("<tr><td><b>File</b></td><td>"); out.println(filePath.getCanonicalPath()); out.println("</tr></td>"); out.println("<tr><td><b>Size</b></td><td>"); out.println(filePath.length()); out.println("</tr></td>"); out.println("<tr><td><b>MD5</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>SHA1</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>Header</b></td><td><pre>"); out.println(file.toString().trim()); out.println("</pre></tr></td>"); if (partFileName.toLowerCase().endsWith(".xml")) { String xml = file.getContent(); String formatted = format(xml); String fileFormatName = fileName + ".formatted"; File fileFormatOut = new File(fileFormatName); FileOutputStream formatOut = new FileOutputStream(fileFormatOut); formatOut.write(formatted.getBytes("UTF-8")); out.println("<tr><td><b>Formatted XML</b></td><td><pre>"); out.println("<a href='/" + (fileFormatName) + "'>" + partFileName + "</a>"); out.println("</pre></tr></td>"); formatOut.close(); } out.println("<table>"); } } out.println("</body>"); out.println("</html>"); } else if (path.startsWith("/sql/") && index != null && searcher != null) { String file = req.getPath().getPath(1); File root = searchEngine.index(searcher).getRoot(); SearchEngine engine = searchEngine.index(searcher); File indexFile = getStoredProcIndexFile(engine.getRoot(), index); File search = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(search, indexFile); FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(source.getName()); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><pre>"); for (String procName : proc.getReferences()) { FindStoredProcs.StoredProc theProc = storedProcProj.getStoredProc(procName); if (theProc != null) { String url = getRelativeURL(root, theProc.getFile()); out.println("<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'><b>" + theProc.getName() + "</b>"); } } out.println("</pre></body>"); out.println("</html>"); } else if (show != null && index != null && searcher != null) { String authentication = req.getValue("Authorization"); if (authentication == null) { resp.setCode(401); resp.setText("Authorization Required"); resp.set("Content-Type", "text/html"); resp.set("WWW-Authenticate", "Basic realm=\"DTS Subversion Repository\""); out.println("<html>"); out.println("<head>"); out.println("401 Authorization Required"); out.println("</head>"); out.println("<body>"); out.println("<h1>401 Authorization Required</h1>"); out.println("</body>"); out.println("</html>"); } else { resp.set("Content-Type", "text/html"); Principal principal = new PrincipalParser(authentication); String file = show; SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File javaIndexFile = getJavaIndexFile(root, index); File storedProcIndexFile = getStoredProcIndexFile(root, index); File sql = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); File javaSource = new File(root, file.replace('/', File.separatorChar)); File canonical = source.getCanonicalFile(); Repository repository = Subversion.login(Scheme.HTTP, principal.getName(), principal.getPassword()); Info info = null; try { info = repository.info(canonical); } catch (Exception e) { e.printStackTrace(); } List<Change> logMessages = new ArrayList<Change>(); try { logMessages = repository.log(canonical); } catch (Exception e) { e.printStackTrace(); } FileInputStream in = new FileInputStream(canonical); List<String> lines = LineStripper.stripLines(in); out.println("<html>"); out.println("<head>"); out.println("<!-- username='" + principal.getName() + "' password='" + principal.getPassword() + "' -->"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); if (info != null) { out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td><tt>" + info.author + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Version</tt></td><td><tt>" + info.version + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>URL</tt></td><td><tt>" + info.location + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Path</tt></td><td><tt>" + canonical + "</tt></td></tr>"); out.println("</table>"); } out.println("<table border='1''>"); out.println("<tr>"); out.println("<td valign='top' bgcolor=\"#C4C4C4\"><pre>"); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(sql, storedProcIndexFile); FindStoredProcs.StoredProc storedProc = null; FindJavaSources.JavaProject project = null; FindJavaSources.JavaClass javaClass = null; List<FindJavaSources.JavaClass> importList = null; if (file.endsWith(".sql")) { storedProc = storedProcProj.getStoredProc(canonical.getName()); } else if (file.endsWith(".java")) { project = FindJavaSources.getProject(root, javaIndexFile); javaClass = project.getClass(source); importList = project.getImports(javaSource); } for (int i = 0; i < lines.size(); i++) { out.println(i); } out.println("</pre></td>"); out.print("<td valign='top'><pre"); out.print(getJavaScript(file)); out.println(">"); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String escaped = escapeHtml(line); if (project != null) { for (FindJavaSources.JavaClass entry : importList) { String className = entry.getClassName(); String fullyQualifiedName = entry.getFullyQualifiedName(); if (line.startsWith("import") && line.indexOf(fullyQualifiedName) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll(fullyQualifiedName + ";", "<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + fullyQualifiedName + "</a>;"); } else if (line.indexOf(className) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll("\\s" + className + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("\\s" + className + "\\{", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("," + className + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("," + className + "\\{", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("\\s" + className + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\(" + className + "\\s", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\s" + className + "\\.", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\(" + className + "\\.", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\s" + className + "\\(", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll("\\(" + className + "\\(", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll("&gt;" + className + ",", "&gt;<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("&gt;" + className + "\\s", "&gt;<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("&gt;" + className + "&lt;", "&gt;<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>&lt;"); escaped = escaped.replaceAll("\\(" + className + "\\);", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>)"); } } } else if (storedProc != null) { Set<String> procSet = storedProc.getTopReferences(); List<String> sortedProcs = new ArrayList(procSet); Collections.sort(sortedProcs, LONGEST_FIRST); for (String procFound : sortedProcs) { if (escaped.indexOf(procFound) != -1) { File nameFile = storedProcProj.getLocation(procFound); if (nameFile != null) { String url = getRelativeURL(root, nameFile); escaped = escaped.replaceAll("\\s" + procFound + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("\\s" + procFound + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("\\s" + procFound + ";", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("," + procFound + "\\s", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("," + procFound + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("," + procFound + ";", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("=" + procFound + "\\s", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("=" + procFound + ",", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("=" + procFound + ";", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("." + procFound + "\\s", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("." + procFound + ",", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("." + procFound + ";", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); } else { System.err.println("NOT FOUND: " + procFound); } } } } out.println(escaped); } out.println("</pre></td>"); out.println("</tr>"); out.println("</table>"); out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Revision</tt></td><td bgcolor=\"#C4C4C4\"><tt>Date</tt></td><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td bgcolor=\"#C4C4C4\"><tt>Comment</tt></td></tr>"); DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); for (Change message : logMessages) { out.printf("<tr><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td></tr>%n", message.version, format.format(message.date).replaceAll("\\s", "&nbsp;"), message.author, message.message); } out.println("</table>"); if (project != null) { out.println("<pre>"); for (FindJavaSources.JavaClass entry : importList) { String url = getRelativeURL(root, entry.getSourceFile()); out.println("import <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + entry.getFullyQualifiedName() + "</a> as " + entry.getClassName()); } out.println("</pre>"); } if (storedProc != null) { out.println("<pre>"); for (String procName : storedProc.getReferences()) { FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(procName); if (proc != null) { String url = getRelativeURL(root, proc.getFile()); out.println("using <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + proc.getName() + "</a>"); } } out.println("</pre>"); } out.println("</form>"); out.println("</body>"); out.println("</html>"); } } else if (path.endsWith(".js") || path.endsWith(".css") || path.endsWith(".formatted")) { path = path.replace('/', File.separatorChar); if (path.endsWith(".formatted")) { resp.set("Content-Type", "text/plain"); } else if (path.endsWith(".js")) { resp.set("Content-Type", "application/javascript"); } else { resp.set("Content-Type", "text/css"); } resp.set("Cache", "no-cache"); WritableByteChannel channelOut = resp.getByteChannel(); File file = new File(".", path).getCanonicalFile(); System.err.println("Serving " + path + " as " + file.getCanonicalPath()); FileChannel sourceChannel = new FileInputStream(file).getChannel(); sourceChannel.transferTo(0, file.length(), channelOut); sourceChannel.close(); channelOut.close(); } else if (env != null && regex != null) { ServerDetails details = config.getEnvironment(env).load(persister, serverDetails != null, fiServerDetails != null, hostDetails != null); List<String> tokens = new ArrayList<String>(); List<Searchable> list = details.search(regex, deep != null, tokens); Collections.sort(tokens, LONGEST_FIRST); for (String token : tokens) { System.out.println("TOKEN: " + token); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, null, null, regex); out.println("<br>Found " + list.size() + " hits for <b>" + regex + "</b>"); out.println("<table border='1''>"); int countIndex = 1; for (Searchable value : list) { out.println(" <tr><td>" + countIndex++ + "&nbsp;<a href='" + value.getSource() + "'><b>" + value.getSource() + "</b></a></td></tr>"); out.println(" <tr><td><pre class='sh_xml'>"); StringWriter buffer = new StringWriter(); persister.write(value, buffer); String text = buffer.toString(); text = escapeHtml(text); for (String token : tokens) { text = text.replaceAll(token, "<font style='BACKGROUND-COLOR: yellow'>" + token + "</font>"); } out.println(text); out.println(" </pre></td></tr>"); } out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } else if (index != null && term != null && term.length() > 0) { out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, term, index, null); if (searcher == null) { searcher = searchEngine.getDefaultSearcher(); } if (refresh != null) { SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File searchIndex = getJavaIndexFile(root, index); FindJavaSources.deleteProject(root, searchIndex); } boolean isRefresh = refresh != null; boolean isGrep = grep != null; boolean isSearchNames = name != null; SearchQuery query = new SearchQuery(index, term, page, isRefresh, isGrep, isSearchNames); List<SearchResult> results = searchEngine.index(searcher).search(query); writeSearchResults(query, searcher, results, out); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<body>"); writeSearchBox(out, searcher, null, null, null); out.println("</body>"); out.println("</html>"); } out.close(); } catch (Exception e) { try { e.printStackTrace(); resp.reset(); resp.setCode(500); resp.setText("Internal Server Error"); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><h1>Internal Server Error</h1><pre>"); e.printStackTrace(out); out.println("</pre></body>"); out.println("</html>"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } } Code Sample 2: @Override public String getHash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); }
00
Code Sample 1: private HttpURLConnection getHttpURLConnection(String bizDocToExecute) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; } Code Sample 2: public char check(String password) { if (captchaRandom.equals("null")) { return 's'; } if (captchaRandom.equals("used")) { return 'm'; } String encryptionBase = secret + captchaRandom; if (!alphabet.equals(ALPHABET_DEFAULT) || letters != LETTERS_DEFAULT) { encryptionBase += ":" + alphabet + ":" + letters; } MessageDigest md5; byte[] digest = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; try { md5 = MessageDigest.getInstance("MD5"); md5.update(encryptionBase.getBytes()); digest = md5.digest(); } catch (NoSuchAlgorithmException e) { } String correctPassword = ""; int index; for (int i = 0; i < letters; i++) { index = (digest[i] + 256) % 256 % alphabet.length(); correctPassword += alphabet.substring(index, index + 1); } if (!password.equals(correctPassword)) { return 'w'; } else { captchaRandom = "used"; return 't'; } }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Override public void run() { try { if (LOG.isDebugEnabled()) { LOG.debug("Backupthread started"); } if (_file.exists()) { _file.delete(); } final ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(_file)); zOut.setLevel(9); final File xmlFile = File.createTempFile("mp3db", ".xml"); final OutputStream ost = new FileOutputStream(xmlFile); final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(ost, "UTF-8"); writer.writeStartDocument("UTF-8", "1.0"); writer.writeCharacters("\n"); writer.writeStartElement("mp3db"); writer.writeAttribute("version", Integer.toString(Main.ENGINEVERSION)); final MediafileDAO mfDAO = new MediafileDAO(); final AlbumDAO aDAO = new AlbumDAO(); final CdDAO cdDAO = new CdDAO(); final CoveritemDAO ciDAO = new CoveritemDAO(); int itemCount = 0; try { itemCount += mfDAO.getCount(); itemCount += aDAO.getCount(); itemCount += cdDAO.getCount(); itemCount += ciDAO.getCount(); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, itemCount)); } catch (final Exception e) { LOG.error("Error getting size", e); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, -1)); } int cdCounter = 0; int mediafileCounter = 0; int albumCounter = 0; int coveritemCounter = 0; int counter = 0; final List<CdIf> data = cdDAO.getCdsOrderById(); if (data.size() > 0) { final Map<Integer, Integer> albums = new HashMap<Integer, Integer>(); final Iterator<CdIf> it = data.iterator(); while (it.hasNext() && !_break) { final CdIf cd = it.next(); final Integer cdId = Integer.valueOf(cdCounter++); writer.writeStartElement(TypeConstants.XML_CD); exportCd(writer, cd, cdId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final List<MediafileIf> files = cd.getMediafiles(); final Iterator<MediafileIf> mfit = files.iterator(); MediafileIf mf; while (mfit.hasNext() && !_break) { mf = mfit.next(); final Integer mfId = Integer.valueOf(mediafileCounter++); writer.writeStartElement(TypeConstants.XML_MEDIAFILE); exportMediafile(writer, mf, mfId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final AlbumIf a = mf.getAlbum(); if (a != null) { Integer inte; if (albums.containsKey(a.getAid())) { inte = albums.get(a.getAid()); writeLink(writer, TypeConstants.XML_ALBUM, inte); } else { inte = Integer.valueOf(albumCounter++); writer.writeStartElement(TypeConstants.XML_ALBUM); exportAlbum(writer, a, inte); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); albums.put(a.getAid(), inte); if (a.hasCoveritems() && !_break) { final List<CoveritemIf> covers = a.getCoveritems(); final Iterator<CoveritemIf> coit = covers.iterator(); while (coit.hasNext() && !_break) { final Integer coveritemId = Integer.valueOf(coveritemCounter++); exportCoveritem(writer, zOut, coit.next(), coveritemId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); } } writer.writeEndElement(); } GenericDAO.getEntityManager().close(); } writer.writeEndElement(); } writer.writeEndElement(); writer.flush(); it.remove(); GenericDAO.getEntityManager().close(); } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); ost.flush(); ost.close(); if (_break) { zOut.close(); _file.delete(); } else { zOut.putNextEntry(new ZipEntry("mp3.xml")); final InputStream xmlIn = FileUtils.openInputStream(xmlFile); IOUtils.copy(xmlIn, zOut); xmlIn.close(); zOut.close(); } xmlFile.delete(); fireStatusEvent(new StatusEvent(this, StatusEventType.FINISH)); } catch (final Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Error backup database", e); } fireStatusEvent(new StatusEvent(this, e, "")); _messenger.fireMessageEvent(new MessageEvent(this, "ERROR", MessageEventTypeEnum.ERROR, GuiStrings.getInstance().getString("error.backup"), e)); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public GEItem lookup(final String itemName) { try { URL url = new URL(GrandExchange.HOST + "/m=itemdb_rs/results.ws?query=" + itemName + "&price=all&members="); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; while ((input = br.readLine()) != null) { if (input.contains("<div id=\"search_results_text\">")) { input = br.readLine(); if (input.contains("Your search for")) { return null; } } else if (input.startsWith("<td><img src=")) { Matcher matcher = GrandExchange.PATTERN.matcher(input); if (matcher.find()) { if (matcher.group(2).contains(itemName)) { return lookup(Integer.parseInt(matcher.group(1))); } } } } } catch (IOException ignored) { } return null; }
11
Code Sample 1: public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { LOG.debug("[sgkim] copy - start"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in = null; OutputStream out = null; try { LOG.debug("[sgkim] srcFS: " + srcFS + ", src: " + src); in = srcFS.open(src); LOG.debug("[sgkim] dstFS: " + dstFS + ", dst: " + dst); out = dstFS.create(dst, overwrite); LOG.debug("[sgkim] copyBytes - start"); IOUtils.copyBytes(in, out, conf, true); LOG.debug("[sgkim] copyBytes - end"); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } LOG.debug("[sgkim] copy - end"); if (deleteSource) { return srcFS.delete(src, true); } else { return true; } } Code Sample 2: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } }
11
Code Sample 1: public static String hash(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 static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
11
Code Sample 1: public static void copyToFileAndCloseStreams(InputStream istr, File destFile) throws IOException { OutputStream ostr = null; try { ostr = new FileOutputStream(destFile); IOUtils.copy(istr, ostr); } finally { if (ostr != null) ostr.close(); if (istr != null) istr.close(); } } Code Sample 2: public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: private String md5(String s) { StringBuffer hexString = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hashPart = Integer.toHexString(0xFF & messageDigest[i]); if (hashPart.length() == 1) { hashPart = "0" + hashPart; } hexString.append(hashPart); } } catch (NoSuchAlgorithmException e) { Log.e(this.getClass().getSimpleName(), "MD5 algorithm not present"); } return hexString != null ? hexString.toString() : null; } Code Sample 2: public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
11
Code Sample 1: public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph tgt = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { tgt = manager.getTargetGraph(); if (tgt != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.ORANGES); factory.visit(tgt); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No target graph loaded."); } } catch (Exception e) { return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); } Code Sample 2: public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
11
Code Sample 1: private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } } Code Sample 2: protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
11
Code Sample 1: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
00
Code Sample 1: public String getUser() { try { HttpGet get = new HttpGet("http://twemoi.status.net/api/account/verify_credentials.xml"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); return ""; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); String salida = sBuf.toString(); String user_name = salida.split("</screen_name>")[0].split("<screen_name>")[1]; return user_name; } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (IOException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } return null; } Code Sample 2: public static void saveFileFromURL(URL url, File destinationFile) throws IOException { FileOutputStream fo = new FileOutputStream(destinationFile); InputStream is = url.openStream(); byte[] data = new byte[1024]; int bytecount = 0; do { fo.write(data, 0, bytecount); bytecount = is.read(data); } while (bytecount > 0); fo.flush(); fo.close(); }
00
Code Sample 1: private Object query(String json) throws IOException, ParseException { String envelope = "{\"qname1\":{\"query\":" + json + "}}"; String urlStr = MQLREADURL + "?queries=" + URLEncoder.encode(envelope, "UTF-8"); if (isDebugging()) { if (echoRequest) System.err.println("Sending:" + envelope); } URL url = new URL(urlStr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", COOKIE + "=" + "\"" + getMetawebCookie() + "\""); con.connect(); InputStream in = con.getInputStream(); Object item = new JSONParser(echoRequest ? new EchoReader(in) : in).object(); in.close(); String code = getString(item, "code"); if (!"/api/status/ok".equals(code)) { throw new IOException("Bad code " + item); } code = getString(item, "qname1.code"); if (!"/api/status/ok".equals(code)) { throw new IOException("Bad code " + item); } return item; } Code Sample 2: public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); }
11
Code Sample 1: private boolean processar(int iCodProd) { String sSQL = null; String sSQLCompra = null; String sSQLInventario = null; String sSQLVenda = null; String sSQLRMA = null; String sSQLOP = null; String sSQLOP_SP = null; String sWhere = null; String sProd = null; String sWhereCompra = null; String sWhereInventario = null; String sWhereVenda = null; String sWhereRMA = null; String sWhereOP = null; String sWhereOP_SP = null; PreparedStatement ps = null; ResultSet rs = null; boolean bOK = false; try { try { sWhere = ""; sProd = ""; if (cbTudo.getVlrString().equals("S")) sProd = "[" + iCodProd + "] "; if (!(txtDataini.getVlrString().equals(""))) { sWhere = " AND DTMOVPROD >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; } sSQL = "DELETE FROM EQMOVPROD WHERE " + "CODEMP=? AND CODPROD=?" + sWhere; state(sProd + "Limpando movimenta��es desatualizadas..."); ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); if ((txtDataini.getVlrString().equals(""))) { sSQL = "UPDATE EQPRODUTO SET SLDPROD=0 WHERE " + "CODEMP=? AND CODPROD=?"; ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); state(sProd + "Limpando saldos..."); sSQL = "UPDATE EQSALDOPROD SET SLDPROD=0 WHERE CODEMP=? AND CODPROD=?"; ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); state(sProd + "Limpando saldos..."); } bOK = true; } catch (SQLException err) { Funcoes.mensagemErro(null, "Erro ao limpar estoques!\n" + err.getMessage(), true, con, err); } if (bOK) { bOK = false; if (!txtDataini.getVlrString().equals("")) { sWhereCompra = " AND C.DTENTCOMPRA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereInventario = " AND I.DATAINVP >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereVenda = " AND V.DTEMITVENDA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereRMA = " AND RMA.DTAEXPRMA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereOP = " AND O.DTFABROP >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereOP_SP = " AND O.DTSUBPROD >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; } else { sWhereCompra = ""; sWhereInventario = ""; sWhereVenda = ""; sWhereRMA = ""; sWhereOP = ""; sWhereOP_SP = ""; } sSQLInventario = "SELECT 'A' TIPOPROC, I.CODEMPPD, I.CODFILIALPD, I.CODPROD," + "I.CODEMPLE, I.CODFILIALLE, I.CODLOTE," + "I.CODEMPTM, I.CODFILIALTM, I.CODTIPOMOV," + "I.CODEMP, I.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "I.CODINVPROD CODMASTER, I.CODINVPROD CODITEM, " + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT ,CAST(NULL AS CHAR(4)) CODNAT," + "I.DATAINVP DTPROC, I.CODINVPROD DOCPROC,'N' FLAG," + "I.QTDINVP QTDPROC, I.PRECOINVP CUSTOPROC, " + "I.CODEMPAX, I.CODFILIALAX, I.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM EQINVPROD I " + "WHERE I.CODEMP=? AND I.CODPROD = ?" + sWhereInventario; sSQLCompra = "SELECT 'C' TIPOPROC, IC.CODEMPPD, IC.CODFILIALPD, IC.CODPROD," + "IC.CODEMPLE, IC.CODFILIALLE, IC.CODLOTE," + "C.CODEMPTM, C.CODFILIALTM, C.CODTIPOMOV," + "C.CODEMP, C.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "C.CODCOMPRA CODMASTER, IC.CODITCOMPRA CODITEM," + "IC.CODEMPNT, IC.CODFILIALNT, IC.CODNAT, " + "C.DTENTCOMPRA DTPROC, C.DOCCOMPRA DOCPROC, C.FLAG," + "IC.QTDITCOMPRA QTDPROC, IC.CUSTOITCOMPRA CUSTOPROC, " + "IC.CODEMPAX, IC.CODFILIALAX, IC.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM CPCOMPRA C,CPITCOMPRA IC " + "WHERE IC.CODCOMPRA=C.CODCOMPRA AND " + "IC.CODEMP=C.CODEMP AND IC.CODFILIAL=C.CODFILIAL AND IC.QTDITCOMPRA > 0 AND " + "C.CODEMP=? AND IC.CODPROD = ?" + sWhereCompra; sSQLOP = "SELECT 'O' TIPOPROC, O.CODEMPPD, O.CODFILIALPD, O.CODPROD," + "O.CODEMPLE, O.CODFILIALLE, O.CODLOTE," + "O.CODEMPTM, O.CODFILIALTM, O.CODTIPOMOV," + "O.CODEMP, O.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA ," + "O.CODOP CODMASTER, CAST(O.SEQOP AS INTEGER) CODITEM," + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "coalesce(oe.dtent,O.DTFABROP) DTPROC, " + "O.CODOP DOCPROC, 'N' FLAG, " + "coalesce(oe.qtdent,O.QTDFINALPRODOP) QTDPROC, " + "( SELECT SUM(PD.CUSTOMPMPROD) FROM PPITOP IT, EQPRODUTO PD " + "WHERE IT.CODEMP=O.CODEMP AND IT.CODFILIAL=O.CODFILIAL AND " + "IT.CODOP=O.CODOP AND IT.SEQOP=O.SEQOP AND " + "PD.CODEMP=IT.CODEMPPD AND PD.CODFILIAL=IT.CODFILIALPD AND " + "PD.CODPROD=IT.CODPROD) CUSTOPROC, " + "O.CODEMPAX, O.CODFILIALAX, O.CODALMOX, oe.seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM PPOP O " + " left outer join ppopentrada oe on oe.codemp=o.codemp and oe.codfilial=o.codfilial and oe.codop=o.codop and oe.seqop=o.seqop " + "WHERE O.QTDFINALPRODOP > 0 AND " + "O.CODEMP=? AND O.CODPROD = ? " + sWhereOP; sSQLOP_SP = "SELECT 'S' TIPOPROC, O.CODEMPPD, O.CODFILIALPD, O.CODPROD," + "O.CODEMPLE, O.CODFILIALLE, O.CODLOTE," + "O.CODEMPTM, O.CODFILIALTM, O.CODTIPOMOV," + "O.CODEMP, O.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA ," + "O.CODOP CODMASTER, CAST(O.SEQOP AS INTEGER) CODITEM," + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "coalesce(o.dtsubprod,Op.DTFABROP) DTPROC, " + "O.CODOP DOCPROC, 'N' FLAG, " + "O.QTDITSP QTDPROC, " + "( SELECT PD.CUSTOMPMPROD FROM EQPRODUTO PD " + "WHERE PD.CODEMP=O.CODEMPPD AND PD.CODFILIAL=O.CODFILIALPD AND " + "PD.CODPROD=O.CODPROD) CUSTOPROC, " + "OP.CODEMPAX, OP.CODFILIALAX, OP.CODALMOX, CAST(NULL AS SMALLINT) as seqent, O.SEQSUBPROD " + "FROM PPOPSUBPROD O, PPOP OP " + "WHERE O.QTDITSP > 0 AND " + "O.CODEMP=OP.CODEMP and O.CODFILIAL=OP.CODFILIAL and O.CODOP=OP.CODOP and O.SEQOP=OP.SEQOP AND " + "O.CODEMP=? AND O.CODPROD = ?" + sWhereOP_SP; sSQLRMA = "SELECT 'R' TIPOPROC, IT.CODEMPPD, IT.CODFILIALPD, IT.CODPROD, " + "IT.CODEMPLE, IT.CODFILIALLE, IT.CODLOTE, " + "RMA.CODEMPTM, RMA.CODFILIALTM, RMA.CODTIPOMOV, " + "RMA.CODEMP, RMA.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "IT.CODRMA CODMASTER, CAST(IT.CODITRMA AS INTEGER) CODITEM, " + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "COALESCE(IT.DTAEXPITRMA,RMA.DTAREQRMA) DTPROC, " + "RMA.CODRMA DOCPROC, 'N' FLAG, " + "IT.QTDEXPITRMA QTDPROC, IT.PRECOITRMA CUSTOPROC," + "IT.CODEMPAX, IT.CODFILIALAX, IT.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM EQRMA RMA ,EQITRMA IT " + "WHERE IT.CODRMA=RMA.CODRMA AND " + "IT.CODEMP=RMA.CODEMP AND IT.CODFILIAL=RMA.CODFILIAL AND " + "IT.QTDITRMA > 0 AND " + "RMA.CODEMP=? AND IT.CODPROD = ?" + sWhereRMA; sSQLVenda = "SELECT 'V' TIPOPROC, IV.CODEMPPD, IV.CODFILIALPD, IV.CODPROD," + "IV.CODEMPLE, IV.CODFILIALLE, IV.CODLOTE," + "V.CODEMPTM, V.CODFILIALTM, V.CODTIPOMOV," + "V.CODEMP, V.CODFILIAL, V.TIPOVENDA, " + "V.CODVENDA CODMASTER, IV.CODITVENDA CODITEM, " + "IV.CODEMPNT, IV.CODFILIALNT, IV.CODNAT, " + "V.DTEMITVENDA DTPROC, V.DOCVENDA DOCPROC, V.FLAG, " + "IV.QTDITVENDA QTDPROC, IV.VLRLIQITVENDA CUSTOPROC, " + "IV.CODEMPAX, IV.CODFILIALAX, IV.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM VDVENDA V ,VDITVENDA IV " + "WHERE IV.CODVENDA=V.CODVENDA AND IV.TIPOVENDA = V.TIPOVENDA AND " + "IV.CODEMP=V.CODEMP AND IV.CODFILIAL=V.CODFILIAL AND " + "IV.QTDITVENDA > 0 AND " + "V.CODEMP=? AND IV.CODPROD = ?" + sWhereVenda; try { state(sProd + "Iniciando reconstru��o..."); sSQL = sSQLInventario + " UNION ALL " + sSQLCompra + " UNION ALL " + sSQLOP + " UNION ALL " + sSQLOP_SP + " UNION ALL " + sSQLRMA + " UNION ALL " + sSQLVenda + " ORDER BY 19,1,20"; System.out.println(sSQL); ps = con.prepareStatement(sSQL); ps.setInt(paramCons.CODEMPIV.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODIV.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPCP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODCP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPOP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODOP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPOPSP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODOPSP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPRM.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODRM.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPVD.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODVD.ordinal(), iCodProd); rs = ps.executeQuery(); bOK = true; while (rs.next() && bOK) { bOK = insereMov(rs, sProd); } rs.close(); ps.close(); state(sProd + "Aguardando grava��o final..."); } catch (SQLException err) { bOK = false; err.printStackTrace(); Funcoes.mensagemErro(null, "Erro ao reconstruir base!\n" + err.getMessage(), true, con, err); } } try { if (bOK) { con.commit(); state(sProd + "Registros processados com sucesso!"); } else { state(sProd + "Registros antigos restaurados!"); con.rollback(); } } catch (SQLException err) { err.printStackTrace(); Funcoes.mensagemErro(null, "Erro ao relizar procedimento!\n" + err.getMessage(), true, con, err); } } finally { sSQL = null; sSQLCompra = null; sSQLInventario = null; sSQLVenda = null; sSQLRMA = null; sWhere = null; sProd = null; sWhereCompra = null; sWhereInventario = null; sWhereVenda = null; sWhereRMA = null; rs = null; ps = null; bRunProcesso = false; btProcessar.setEnabled(true); } return bOK; } Code Sample 2: @Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); try { String name = "nixspam-ip.dump.gz"; String f = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { org.apache.commons.io.FileUtils.forceMkdir(new File(f)); } catch (IOException ex) { fatal("IOException", ex); } f += "/" + name; String url = "http://www.dnsbl.manitu.net/download/" + name; debug("(1) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); com.utils.IOUtil.unzip(f, f.replace(".gz", "")); File file_to_read = new File(f.replaceAll(".gz", "")); BigFile lines = null; try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Excpetion", e); return; } try { Statement stat = conn_url.createStatement(); stat.executeUpdate(properties.get("query_delete")); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } boolean ok = true; int i = 0; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.substring(line.indexOf(" ")); line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } boolean del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); name = "spam-ip.com_" + DateTimeUtil.getNowWithFormat("MM-dd-yyyy") + ".csv"; f = this.path_app_root + "/" + this.properties.get("dir") + "/"; org.apache.commons.io.FileUtils.forceMkdir(new File(f)); f += "/" + name; url = "http://spam-ip.com/csv_dump/" + name; debug("(2) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); file_to_read = new File(f); try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Exception", e); return; } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } ok = true; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.split(",")[1]; line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); if (ok) { debug("Import della BlackList Concluso tot righe: " + i); try { conn_url.commit(); } catch (SQLException e) { fatal("SQLException", e); } } else { fatal("Problemi con la Blacklist"); } try { conn_url.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { Statement stat = this.conn_url.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } } catch (IOException ex) { fatal("IOException", ex); } debug("End execute job " + this.getClass().getName()); }
11
Code Sample 1: void serialize(ZipOutputStream out) throws IOException { if ("imsmanifest.xml".equals(getFullName())) return; out.putNextEntry(new ZipEntry(getFullName())); IOUtils.copy(getDataStream(), out); out.closeEntry(); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); } Code Sample 2: public void copyHashAllFilesToDirectory(String baseDirStr, Hashtable newNamesTable, String destDirStr) throws Exception { if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(baseDirStr); if (null == newNamesTable) { newNamesTable = new Hashtable(); } BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if ((baseDir.exists()) && (baseDir.isDirectory())) { if (!newNamesTable.isEmpty()) { Enumeration enumFiles = newNamesTable.keys(); while (enumFiles.hasMoreElements()) { String newName = (String) enumFiles.nextElement(); String oldPathName = (String) newNamesTable.get(newName); if ((newName != null) && (!"".equals(newName)) && (oldPathName != null) && (!"".equals(oldPathName))) { String newPathFileName = destDirStr + sep + newName; String oldPathFileName = baseDirStr + sep + oldPathName; if (oldPathName.startsWith(sep)) { oldPathFileName = baseDirStr + oldPathName; } File f = new File(oldPathFileName); if ((f.exists()) && (f.isFile())) { in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { } } } } else { } } else { throw new Exception("Base (baseDirStr) dir not exist !"); } }
00
Code Sample 1: public void delete(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); if (urlConnection instanceof HttpURLConnection) { final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setRequestMethod("DELETE"); int responseCode = httpURLConnection.getResponseCode(); switch(responseCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_ACCEPTED: case HttpURLConnection.HTTP_NO_CONTENT: { break; } default: { throw new IOException("DELETE failed with HTTP response code " + responseCode); } } } else { throw new IOException("Delete is not supported for " + uri); } } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private void addConfigurationResource(final String fileName, final boolean ensureLoaded) { try { final ClassLoader cl = this.getClass().getClassLoader(); final Properties p = new Properties(); final URL url = cl.getResource(fileName); if (url == null) { throw new NakedObjectRuntimeException("Failed to load configuration resource: " + fileName); } p.load(url.openStream()); configuration.add(p); } catch (Exception e) { if (ensureLoaded) { throw new NakedObjectRuntimeException(e); } LOG.debug("Resource: " + fileName + " not found, but not needed"); } } Code Sample 2: static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource(file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; }
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 static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public static EXISchema getEXISchema(String fileName, Class<?> cls, EXISchemaFactoryErrorHandler compilerErrorHandler) throws IOException, ClassNotFoundException, EXISchemaFactoryException { EXISchemaFactory schemaCompiler = new EXISchemaFactory(); schemaCompiler.setCompilerErrorHandler(compilerErrorHandler); InputSource inputSource = null; if (fileName != null) { URL url; if ((url = cls.getResource(fileName)) != null) { inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); } else throw new RuntimeException("File '" + fileName + "' not found."); } EXISchema compiled = schemaCompiler.compile(inputSource); InputStream serialized = serializeSchema(compiled); return loadSchema(serialized); } Code Sample 2: public synchronized String encrypt(String plaintext) { if (plaintext == null || plaintext.equals("")) { return plaintext; } String hash = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); hash = Base64.encodeBase64String(raw).replaceAll("\r\n", ""); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage()); } return hash; }
00
Code Sample 1: public void moveRowUp(int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt); if ((row < 2) || (row > max)) throw new IllegalArgumentException("Row number not between 2 and " + max); stmt.executeUpdate("update WordClassifications set Rank = -1 where Rank = " + row); stmt.executeUpdate("update WordClassifications set Rank = " + row + " where Rank = " + (row - 1)); stmt.executeUpdate("update WordClassifications set Rank = " + (row - 1) + " where Rank = -1"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public static InputStream getResourceRelativeAsStream(final String name, final Class context) { final URL url = getResourceRelative(name, context); if (url == null) { return null; } try { return url.openStream(); } catch (IOException e) { return null; } }
11
Code Sample 1: @SuppressWarnings("unchecked") public ArrayList<GmailContact> getAllContacts() throws GmailException { String query = properties.getString("export_page"); query = query.replace("[RANDOM_INT]", "" + random.nextInt()); int statusCode = -1; GetMethod get = new GetMethod(query); if (log.isInfoEnabled()) log.info("getting all contacts ..."); try { statusCode = client.executeMethod(get); if (statusCode != 200) throw new GmailException("In contacts export page: Status code expected: 200 -> Status code returned: " + statusCode); } catch (HttpException e) { throw new GmailException("HttpException in contacts export page:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in contacts export page:" + e.getMessage()); } finally { get.releaseConnection(); } if (log.isTraceEnabled()) log.trace("accessing contacts export page successful..."); String query_post = properties.getString("outlook_export_page"); PostMethod post = new PostMethod(query_post); post.addRequestHeader("Accept-Encoding", "gzip,deflate"); post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.8"); NameValuePair[] data = { new NameValuePair("at", getCookie("GMAIL_AT")), new NameValuePair("ecf", "o"), new NameValuePair("ac", "Export Contacts") }; post.setRequestBody(data); if (log.isTraceEnabled()) log.trace("getting contacts csv file..."); try { statusCode = client.executeMethod(post); if (statusCode != 200) throw new GmailException("In csv file post: Status code expected: 200 -> Status code returned: " + statusCode); if (log.isTraceEnabled()) log.trace("Gmail: csv charset: " + post.getResponseCharSet()); GMAIL_OUTPUT_CHARSET = post.getResponseCharSet(); InputStreamReader isr = new InputStreamReader(new GZIPInputStream(post.getResponseBodyAsStream()), post.getResponseCharSet()); CSVReader reader = new CSVReader(isr); List csvEntries = reader.readAll(); reader.close(); ArrayList<GmailContact> contacts = new ArrayList<GmailContact>(); MessageDigest m = MessageDigest.getInstance("MD5"); if (log.isTraceEnabled()) log.trace("creating Gmail contacts..."); for (int i = 1; i < csvEntries.size(); i++) { GmailContact contact = new GmailContact(); String[] value = (String[]) csvEntries.get(i); for (int j = 0; j < value.length; j++) { switch(j) { case 0: contact.setName(value[j]); break; case 1: contact.setEmail(value[j]); if (contact.getName() == null) contact.setIdName(value[j]); else contact.setIdName(contact.getName() + value[j]); break; case 2: contact.setNotes(value[j]); break; case 3: contact.setEmail2(value[j]); break; case 4: contact.setEmail3(value[j]); break; case 5: contact.setMobilePhone(value[j]); break; case 6: contact.setPager(value[j]); break; case 7: contact.setCompany(value[j]); break; case 8: contact.setJobTitle(value[j]); break; case 9: contact.setHomePhone(value[j]); break; case 10: contact.setHomePhone2(value[j]); break; case 11: contact.setHomeFax(value[j]); break; case 12: contact.setHomeAddress(value[j]); break; case 13: contact.setBusinessPhone(value[j]); break; case 14: contact.setBusinessPhone2(value[j]); break; case 15: contact.setBusinessFax(value[j]); break; case 16: contact.setBusinessAddress(value[j]); break; case 17: contact.setOtherPhone(value[j]); break; case 18: contact.setOtherFax(value[j]); break; case 19: contact.setOtherAddress(value[j]); break; } } m.update(contact.toString().getBytes()); if (log.isTraceEnabled()) log.trace("setting Md5 Hash..."); contact.setMd5Hash(new BigInteger(m.digest()).toString()); contacts.add(contact); } if (log.isTraceEnabled()) log.trace("Mapping contacts uid..."); Collections.sort(contacts); ArrayList<GmailContact> idList = getAllContactsID(); for (int i = 0; i < idList.size(); i++) { contacts.get(i).setId(idList.get(i).getId()); } if (log.isInfoEnabled()) log.info("getting all contacts info successful..."); return contacts; } catch (HttpException e) { throw new GmailException("HttpException in csv file post:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in csv file post:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new GmailException("No such md5 algorithm " + e.getMessage()); } finally { post.releaseConnection(); } } Code Sample 2: public static String getDigest(String input) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(input.getBytes()); byte[] outDigest = md5.digest(); StringBuffer outBuf = new StringBuffer(33); for (int i = 0; i < outDigest.length; i++) { byte b = outDigest[i]; int hi = (b >> 4) & 0x0f; outBuf.append(MD5Digest.hexTab[hi]); int lo = b & 0x0f; outBuf.append(MD5Digest.hexTab[lo]); } return outBuf.toString(); }
11
Code Sample 1: void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); try { for (InputStream inputStream : entries.keySet()) { ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream))); out.putNextEntry(zipEntry); IOUtils.copy(inputStream, out); out.closeEntry(); inputStream.close(); if (monitor != null) monitor.worked(1); } } finally { IOUtils.closeQuietly(out); } }
00
Code Sample 1: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } Code Sample 2: public void displayItems() throws IOException { URL url = new URL(SNIPPETS_FEED + "?bq=" + URLEncoder.encode(QUERY, "UTF-8") + "&key=" + DEVELOPER_KEY); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = httpConnection.getInputStream(); int ch; while ((ch = inputStream.read()) > 0) { System.out.print((char) ch); } }
00
Code Sample 1: private ArrayList<Stock> fetchStockData(Stock[] stocks) throws IOException { Log.d(TAG, "Fetching stock data from Yahoo"); ArrayList<Stock> newStocks = new ArrayList<Stock>(stocks.length); if (stocks.length > 0) { StringBuilder sb = new StringBuilder(); for (Stock stock : stocks) { sb.append(stock.getSymbol()); sb.append('+'); } sb.deleteCharAt(sb.length() - 1); String urlStr = "http://finance.yahoo.com/d/quotes.csv?f=sb2n&s=" + sb.toString(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlStr.toString()); HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); int i = 0; Log.d(TAG, "Parsing stock data from Yahoo"); while (line != null) { Log.d(TAG, "Parsing: " + line); String[] values = line.split(","); Stock stock = new Stock(stocks[i], stocks[i].getId()); stock.setCurrentPrice(Double.parseDouble(values[1])); stock.setName(values[2]); Log.d(TAG, "Parsed Stock: " + stock); newStocks.add(stock); line = reader.readLine(); i++; } } return newStocks; } Code Sample 2: public void readDirectoryFrom(String urlString) throws Exception { URL url = new URL(urlString + DIR_INFO_FIENAME); PushbackInputStream in = new PushbackInputStream(new BufferedInputStream(url.openStream())); readDataFrom(in); TextToken t = TextToken.nextToken(in); while (t != null && t.isString()) { DirectoryInfoModel dir = addDirectory(new DirectoryInfo(t.getString())); dir.setUrl(urlString + t.getString() + '/'); t = TextToken.nextToken(in); } in.close(); }
00
Code Sample 1: public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public String sendRequestAndGetNormalStringOutPut(java.lang.String servletName, java.lang.String request) { String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } String response = ""; try { System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); String req1xml = request; java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println(req1xml); dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8"); int n = -1; while ((n = br.read()) != -1) response += (char) n; } catch (java.net.ConnectException conexp) { javax.swing.JOptionPane.showMessageDialog(null, "<html>Could not establish connection with the NewGenLib server, " + "<br>These might be the possible reasons." + "<br><li>Check the network connectivity between this machine and the server." + "<br><li>Check whether NewGenLib server is running on the server machine." + "<br><li>NewGenLib server might not have initialized properly. In this case" + "<br>go to server machine, open NewGenLibDesktop Application," + "<br> utility ->Send log to NewGenLib Customer Support</html>", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE); } catch (Exception exp) { exp.printStackTrace(System.out); TroubleShootConnectivity troubleShoot = new TroubleShootConnectivity(); } return response; }
00
Code Sample 1: private void getLines(PackageManager pm) throws PackageManagerException { final Pattern p = Pattern.compile("\\s*deb\\s+(ftp://|http://)(\\S+)\\s+((\\S+\\s*)*)(./){0,1}"); Matcher m; if (updateUrlAndFile == null) updateUrlAndFile = new ArrayList<UrlAndFile>(); BufferedReader f; String protocol; String host; String shares; String adress; try { f = new BufferedReader(new FileReader(sourcesList)); while ((protocol = f.readLine()) != null) { m = p.matcher(protocol); if (m.matches()) { protocol = m.group(1); host = m.group(2); if (m.group(3).trim().equalsIgnoreCase("./")) shares = ""; else shares = m.group(3).trim(); if (shares == null) adress = protocol + host; else { shares = shares.replace(" ", "/"); if (!host.endsWith("/") && !shares.startsWith("/")) host = host + "/"; adress = host + shares; while (adress.contains("//")) adress = adress.replace("//", "/"); adress = protocol + adress; } if (!adress.endsWith("/")) adress = adress + "/"; String changelogdir = adress; changelogdir = changelogdir.substring(changelogdir.indexOf("//") + 2); if (changelogdir.endsWith("/")) changelogdir = changelogdir.substring(0, changelogdir.lastIndexOf("/")); changelogdir = changelogdir.replace('/', '_'); changelogdir = changelogdir.replaceAll("\\.", "_"); changelogdir = changelogdir.replaceAll("-", "_"); changelogdir = changelogdir.replaceAll(":", "_COLON_"); adress = adress + "Packages.gz"; final String serverFileLocation = adress.replaceAll(":", "_COLON_"); final NameFileLocation nfl = new NameFileLocation(); try { final GZIPInputStream in = new GZIPInputStream(new ConnectToServer(pm).getInputStream(adress)); final String rename = new File(nfl.rename(serverFileLocation, listsDir)).getCanonicalPath(); final FileOutputStream out = new FileOutputStream(rename); final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); final File file = new File(rename); final UrlAndFile uaf = new UrlAndFile(protocol + host, file, changelogdir); updateUrlAndFile.add(uaf); } catch (final Exception e) { final String message = "URL: " + adress + " caused exception"; if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } } f.close(); } catch (final FileNotFoundException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("sourcesList.corrupt", "Entry not found sourcesList.corrupt"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } catch (final IOException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("SearchForServerFile.getLines.IOException", "Entry not found SearchForServerFile.getLines.IOException"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } Code Sample 2: public void callBatch(final List<JsonRpcClient.Call> calls, final JsonRpcClient.BatchCallback callback) { HttpPost httpPost = new HttpPost(mRpcUrl); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try { for (int i = 0; i < calls.size(); i++) { JsonRpcClient.Call call = calls.get(i); JSONObject callJson = new JSONObject(); callJson.put("method", call.getMethodName()); if (call.getParams() != null) { JSONObject callParams = (JSONObject) call.getParams(); @SuppressWarnings("unchecked") Iterator<String> keysIterator = callParams.keys(); String key; while (keysIterator.hasNext()) { key = keysIterator.next(); callJson.put(key, callParams.get(key)); } } callsJson.put(i, callJson); } requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "POST request: " + requestJson.toString()); } } catch (JSONException e) { } catch (UnsupportedEncodingException e) { } try { HttpResponse httpResponse = mHttpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "POST response: " + sb.toString()); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); Object[] resultData = new Object[calls.size()]; for (int i = 0; i < calls.size(); i++) { JSONObject result = resultsJson.getJSONObject(i); if (result.has("error")) { callback.onError(i, new JsonRpcException((int) result.getInt("error"), calls.get(i).getMethodName(), result.getString("message"), null)); resultData[i] = null; } else { resultData[i] = result.get("data"); } } callback.onData(resultData); } else { callback.onError(-1, new JsonRpcException(-1, "Received HTTP status code other than HTTP 2xx: " + httpResponse.getStatusLine().getReasonPhrase())); } } catch (IOException e) { Log.e("JsonRpcJavaClient", e.getMessage()); e.printStackTrace(); } catch (JSONException e) { Log.e("JsonRpcJavaClient", "Error parsing server JSON response: " + e.getMessage()); e.printStackTrace(); } }
11
Code Sample 1: public String getCipherString(String source) throws CadenaNoCifradaException { String encryptedSource = null; MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(source.getBytes(encoding), 0, source.length()); sha1hash = md.digest(); encryptedSource = convertToHex(sha1hash); } catch (Exception e) { throw new CadenaNoCifradaException(e); } return encryptedSource; } Code Sample 2: public static String getMd5Digest(String pInput) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(pInput.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032x", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
00
Code Sample 1: public void createCodeLocation() { List<IClasspathEntry> classpathEntries = new UniqueEList<IClasspathEntry>(); project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectname); try { IProjectDescription projectDescription = null; IJavaProject javaProject = JavaCore.create(project); if (project.exists()) { project.delete(true, null); } projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectname); project.create(projectDescription, new NullProgressMonitor()); String[] natureIds = projectDescription.getNatureIds(); if (natureIds == null) { natureIds = new String[] { JavaCore.NATURE_ID }; } else { boolean hasJavaNature = false; boolean hasPDENature = false; for (int i = 0; i < natureIds.length; ++i) { if (JavaCore.NATURE_ID.equals(natureIds[i])) { hasJavaNature = true; } if ("org.eclipse.pde.PluginNature".equals(natureIds[i])) { hasPDENature = true; } } if (!hasJavaNature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = JavaCore.NATURE_ID; } if (!hasPDENature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature"; } } projectDescription.setNatureIds(natureIds); ICommand[] builders = projectDescription.getBuildSpec(); if (builders == null) { builders = new ICommand[0]; } boolean hasManifestBuilder = false; boolean hasSchemaBuilder = false; for (int i = 0; i < builders.length; ++i) { if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName())) { hasManifestBuilder = true; } if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName())) { hasSchemaBuilder = true; } } if (!hasManifestBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder"); } if (!hasSchemaBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder"); } projectDescription.setBuildSpec(builders); project.open(new NullProgressMonitor()); project.setDescription(projectDescription, new NullProgressMonitor()); sourceContainer = project.getFolder("src"); sourceContainer.create(false, true, new NullProgressMonitor()); IClasspathEntry sourceClasspathEntry = JavaCore.newSourceEntry(new Path("/" + projectname + "/src")); classpathEntries.add(0, sourceClasspathEntry); String jreContainer = JavaRuntime.JRE_CONTAINER; String complianceLevel = CodeGenUtil.EclipseUtil.getJavaComplianceLevel(project); if ("1.5".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"; } else if ("1.6".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"; } classpathEntries.add(JavaCore.newContainerEntry(new Path(jreContainer))); classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); javaProject.setOutputLocation(new Path("/" + projectname + "/bin"), new NullProgressMonitor()); javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), new NullProgressMonitor()); } catch (CoreException e) { e.printStackTrace(); CodeGenEcorePlugin.INSTANCE.log(e); } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
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 sourceFile, File destFile) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(sourceFile); os = new FileOutputStream(destFile); IOUtils.copy(is, os); } finally { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
00
Code Sample 1: public ProgramProfilingSymbol updateProgramProfilingSymbol(int id, int configID, int programSymbolID) throws AdaptationException { ProgramProfilingSymbol pps = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE ProgramProfilingSymbols SET " + "projectDeploymentConfigurationID = " + configID + ", " + "programSymbolID = " + programSymbolID + ", " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from ProgramProfilingSymbols WHERE " + "id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program profiling " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } pps = getProfilingSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramProfilingSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return pps; } Code Sample 2: public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
11
Code Sample 1: public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.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(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } Code Sample 2: public static int save(File inputFile, File outputFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFile); outputFile.getParentFile().mkdirs(); out = new FileOutputStream(outputFile); } catch (Exception e) { e.getMessage(); } try { return IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { if (out != null) { out.close(); } } catch (IOException ioe) { ioe.getMessage(); } try { if (in != null) { in.close(); } } catch (IOException ioe) { ioe.getMessage(); } } }
00
Code Sample 1: private void constructDialogContent(Composite parent) { SashForm splitter = new SashForm(parent, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(GridData.FILL_BOTH)); Group fragmentsGroup = new Group(splitter, SWT.NONE); fragmentsGroup.setLayout(new GridLayout(1, false)); fragmentsGroup.setText("Result Fragments"); fragmentsTable = CheckboxTableViewer.newCheckList(fragmentsGroup, SWT.NONE); fragmentsTable.getTable().setLayoutData(new GridData(GridData.FILL_BOTH)); fragmentsTable.setContentProvider(new ArrayContentProvider()); fragmentsTable.setLabelProvider(new LabelProvider() { public Image getImage(Object element) { return JFaceResources.getImage(WsmoImageRegistry.INSTANCE_ICON); } public String getText(Object element) { if (element == null) { return ""; } if (element instanceof ProcessFragment) { ProcessFragment frag = (ProcessFragment) element; String label = (frag.getName() == null) ? " <no-fragment-name>" : frag.getName(); if (frag.getDescription() != null) { label += " [" + Utils.normalizeSpaces(frag.getDescription()) + ']'; } return label; } return element.toString(); } }); fragmentsTable.setInput(results.toArray()); final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { if (false == GUIHelper.containsCursor(fragmentsTable.getTable())) { return; } if (false == fragmentsTable.getSelection().isEmpty()) { menuMgr.add(new Action("Edit Name") { public void run() { doEditName(); } }); menuMgr.add(new Action("Edit Description") { public void run() { doEditDescription(); } }); menuMgr.add(new Separator()); } menuMgr.add(new Action("Select All") { public void run() { fragmentsTable.setAllChecked(true); updateSelectionMonitor(); } }); menuMgr.add(new Separator()); menuMgr.add(new Action("Unselect All") { public void run() { fragmentsTable.setAllChecked(false); updateSelectionMonitor(); } }); } }); fragmentsTable.getTable().setMenu(menuMgr.createContextMenu(fragmentsTable.getTable())); fragmentsTable.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updatePreviewPanel((IStructuredSelection) event.getSelection()); } }); new FragmentsToolTipProvider(this.fragmentsTable.getTable()); Group previewGroup = new Group(splitter, SWT.NONE); previewGroup.setLayout(new GridLayout(1, false)); previewGroup.setText("Fragment Preview"); createZoomToolbar(previewGroup); previewArea = new Composite(previewGroup, SWT.BORDER); previewArea.setLayoutData(new GridData(GridData.FILL_BOTH)); previewArea.setLayout(new GridLayout(1, false)); viewer = new ScrollingGraphicalViewer(); viewer.createControl(previewArea); ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.getControl().setBackground(ColorConstants.listBackground); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); ZoomManager zoomManager = rootEditPart.getZoomManager(); ArrayList<String> zoomContributions = new ArrayList<String>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); zoomManager.setZoomLevelContributions(zoomContributions); zoomManager.setZoomLevels(new double[] { 0.25, 0.33, 0.5, 0.75, 1.0 }); zoomManager.setZoom(1.0); Composite businessGoalPanel = new Composite(previewGroup, SWT.NONE); businessGoalPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); businessGoalPanel.setLayout(new GridLayout(4, false)); Label lab = new Label(businessGoalPanel, SWT.NONE); lab.setText("Process goal:"); bpgIRI = new Text(businessGoalPanel, SWT.BORDER | SWT.READ_ONLY); bpgIRI.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectBpgButton = new Button(businessGoalPanel, SWT.NONE); selectBpgButton.setText("Select"); selectBpgButton.setEnabled(false); selectBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { doSelectProcessGoal(); } }); clearBpgButton = new Button(businessGoalPanel, SWT.NONE); clearBpgButton.setText("Clear"); clearBpgButton.setEnabled(false); clearBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { IStructuredSelection sel = (IStructuredSelection) fragmentsTable.getSelection(); if (sel.isEmpty() || false == sel.getFirstElement() instanceof ProcessFragment) { return; } ((ProcessFragment) sel.getFirstElement()).setBusinessProcessGoal(null); updatePreviewPanel(sel); } }); splitter.setWeights(new int[] { 1, 2 }); } Code Sample 2: public static String getMD5(String text) { if (text == null) { return null; } String result = null; try { MessageDigest md5 = MessageDigest.getInstance(ALG_MD5); md5.update(text.getBytes(ENCODING)); result = "" + new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
00
Code Sample 1: public static InputStream getNotCacheResourceAsStream(final String fileName) { if ((fileName.indexOf("file:") >= 0) || (fileName.indexOf(":/") > 0)) { try { URL url = new URL(fileName); return new BufferedInputStream(url.openStream()); } catch (Exception e) { return null; } } return new ByteArrayInputStream(getNotCacheResource(fileName).getData()); } Code Sample 2: @Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } }
00
Code Sample 1: public static void main(String[] args) throws Exception { URL url = new URL("http://www.sohu.com"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is, Charset.forName("GB18030")); FileOutputStream fos = new FileOutputStream("gen/sohu2.html"); OutputStreamWriter osw = new OutputStreamWriter(fos); char[] b = new char[2048]; int temp; while (-1 != (temp = isr.read(b, 0, b.length))) { osw.write(b); } osw.close(); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; } Code Sample 2: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
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: public void run() { XmlFilesFilter filter = new XmlFilesFilter(); String pathTemp = Settings.get("vo_store.databaseMetaCollection"); String sectionName = pathTemp.substring(1, pathTemp.indexOf("/", 2)); String templateName = VOAccess.getElementByName(settingsDB, "TEMPLATE", sectionName); String schemaName = VOAccess.getElementByName(settingsDB, "SCHEMA", sectionName); byte[] buf = new byte[1024]; Hashtable templateElements = null; try { URL xmlTemplateUrl = new URL(httpURI + settingsDB + "/" + templateName); URL getDocPathsAndValuesXslUrl = new URL(httpURI + settingsDB + "/" + "getDocPathsValuesAndDisplays.xsl"); org.w3c.dom.Document curTemplateXml = VOAccess.readDocument(xmlTemplateUrl); DOMResult templateResult = new DOMResult(); InputStream tempInput = getDocPathsAndValuesXslUrl.openStream(); javax.xml.transform.sax.SAXSource tempXslSource = new javax.xml.transform.sax.SAXSource(new org.xml.sax.InputSource(tempInput)); Transformer trans = TransformerFactory.newInstance().newTransformer(tempXslSource); trans.setParameter("schemaUrl", httpURI + settingsDB + "/" + schemaName); trans.transform(new javax.xml.transform.dom.DOMSource(curTemplateXml), templateResult); tempInput.close(); templateElements = VOAccess.displaysToHashtable(templateResult); ((CollectionManagementService) CollectionsManager.getService(xmldbURI + rootDB, false, "CollectionManager")).createCollection(rootDB + pathTemp); } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); } while (true) { File[] fileList = sourceMetaFilesDir.listFiles(filter); for (int i = 0; i < Math.min(fileList.length, 500); i++) { File newFile = fileList[i]; try { Document metaDoc = build.build(newFile); Element metaElm = metaDoc.getRootElement(); String dataFileName = metaElm.getChildText("Content"), previewFileName = metaElm.getChildText("Preview"); String objId = VOAccess.getUniqueId(); metaElm.getChild("Content").setText("videostore?type=doc&objId=" + objId); metaElm.getChild("Preview").setText("videostore?type=preview&objId=" + objId); boolean found = false; for (Iterator it = sourceDataFilesDirs.iterator(); it.hasNext() && !found; ) { String sourceDataFilesDir = (String) it.next(); File dataInput = new File(sourceDataFilesDir + "/" + dataFileName); if (dataInput.exists()) { found = true; BufferedInputStream inp = new BufferedInputStream(new FileInputStream(dataInput)); FileOutputStream outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".dat")); int read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); dataInput = new File(sourceDataFilesDir + "/" + previewFileName); inp = new BufferedInputStream(new FileInputStream(dataInput)); outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".jpg")); read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); curDirWriteTo++; if (curDirWriteTo >= targetDataFilesDirs.size()) { curDirWriteTo = 0; } } } if (!found) { newFile.renameTo(new File(newFile.getAbsolutePath() + ".not_found")); } else { String title = getValueByPath((String) templateElements.get("title"), metaDoc.getRootElement()); String description = getValueByPath((String) templateElements.get("description"), metaDoc.getRootElement()); String onlink = ""; if (null != templateElements.get("onlink")) { onlink = getValueByPath((String) templateElements.get("onlink"), metaDoc.getRootElement()); } String ncover = ""; if (null != templateElements.get("ncover")) { ncover = getValueByPath((String) templateElements.get("ncover"), metaDoc.getRootElement()); } String wcover = ""; if (null != templateElements.get("wcover")) { wcover = getValueByPath((String) templateElements.get("wcover"), metaDoc.getRootElement()); } String ecover = ""; if (null != templateElements.get("ecover")) { ecover = getValueByPath((String) templateElements.get("ecover"), metaDoc.getRootElement()); } String scover = ""; if (null != templateElements.get("scover")) { scover = getValueByPath((String) templateElements.get("scover"), metaDoc.getRootElement()); } String datefrom = ""; if (null != templateElements.get("datefrom")) { datefrom = getValueByPath((String) templateElements.get("datefrom"), metaDoc.getRootElement()); } String dateto = ""; if (null != templateElements.get("dateto")) { dateto = getValueByPath((String) templateElements.get("dateto"), metaDoc.getRootElement()); } String previewimg = ""; if (null != templateElements.get("previewimg")) { previewimg = getValueByPath((String) templateElements.get("previewimg"), metaDoc.getRootElement()); } String discRestr = "false"; String votingRestr = "false"; datefrom = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); dateto = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); Hashtable discussionFields = new Hashtable(); discussionFields.put("OBJECT_ID", objId); discussionFields.put("AUTHOR_ID", "auto"); discussionFields.put("AUTHOR_NAME", "auto"); discussionFields.put("OBJECT_SECTION", sectionName); discussionFields.put("OBJECT_PATH", pathTemp); discussionFields.put("FILE_PATH", ""); discussionFields.put("TITLE", title); discussionFields.put("DESCRIPTION", description); discussionFields.put("ONLINK", onlink); discussionFields.put("NCOVER", ncover); discussionFields.put("ECOVER", ecover); discussionFields.put("SCOVER", scover); discussionFields.put("WCOVER", wcover); discussionFields.put("PERIOD_START", datefrom); discussionFields.put("PERIOD_END", dateto); discussionFields.put("PREVIEW_IMG", previewimg); discussionFields.put("DISCUSSRESTRICTION", discRestr); discussionFields.put("VOTINGRESTRICTION", votingRestr); VOAccess.createDiscussionFile(discussionFields); VOAccess.updateLastItem(objId, sectionName); Collection col = CollectionsManager.getCollection(rootDB + pathTemp, true); XMLResource document = (XMLResource) col.createResource(objId + ".xml", XMLResource.RESOURCE_TYPE); document.setContent(outXml.outputString(metaElm)); col.storeResource(document); Indexer.index(objId); newFile.delete(); } } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); newFile.renameTo(new File(newFile.getAbsolutePath() + ".bad")); } } try { this.sleep(600000); } catch (InterruptedException ex1) { ex1.printStackTrace(); } } }
00
Code Sample 1: @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dataSetURL = request.getParameter("datasetURL"); String contentType = request.getParameter("contentType"); String studyUID = request.getParameter("studyUID"); String seriesUID = request.getParameter("seriesUID"); String objectUID = request.getParameter("objectUID"); dataSetURL += "&contentType=" + contentType + "&studyUID=" + studyUID + "&seriesUID=" + seriesUID + "&objectUID=" + objectUID; dataSetURL = dataSetURL.replace("+", "%2B"); InputStream resultInStream = null; OutputStream resultOutStream = response.getOutputStream(); try { URL url = new URL(dataSetURL); resultInStream = url.openStream(); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = resultInStream.read(buffer)) != -1) { resultOutStream.write(buffer, 0, bytes_read); } resultOutStream.flush(); resultOutStream.close(); resultInStream.close(); } catch (Exception e) { log.error("Unable to read and send the DICOM dataset page", e); } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); }
11
Code Sample 1: public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); try { for (InputStream inputStream : entries.keySet()) { ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream))); out.putNextEntry(zipEntry); IOUtils.copy(inputStream, out); out.closeEntry(); inputStream.close(); if (monitor != null) monitor.worked(1); } } finally { IOUtils.closeQuietly(out); } } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: public String download(String urlStr) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); System.out.println(buffer); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); } Code Sample 2: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
11
Code Sample 1: private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }