label
int64
0
1
func1
stringlengths
173
53.1k
func2
stringlengths
173
53.1k
id
int64
0
901k
1
public static void copyFile(File srcFile, File desFile) throws IOException { AssertUtility.notNull(srcFile); AssertUtility.notNull(desFile); FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(desFile); try { FileChannel srcChannel = fis.getChannel(); FileChannel dstChannel = fos.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } finally { fis.close(); fos.close(); } }
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[8192]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
900,200
1
public static void copy(final String source, final String dest) { final File s = new File(source); final File w = new File(dest); try { final FileInputStream in = new FileInputStream(s); final FileOutputStream out = new FileOutputStream(w); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } }
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) { } } }
900,201
1
private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); }
public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
900,202
1
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
public static void compressAll(File dir, File file) throws IOException { if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.setLevel(0); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytesRead; for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); }
900,203
1
public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } }
private void doTask() { try { log("\n\n\n\n\n\n\n\n\n"); log(" ================================================="); log(" = Starting PSCafePOS ="); log(" ================================================="); log(" = An open source point of sale system ="); log(" = for educational organizations. ="); log(" ================================================="); log(" = General Information ="); log(" = http://pscafe.sourceforge.net ="); log(" = Free Product Support ="); log(" = http://www.sourceforge.net/projects/pscafe ="); log(" ================================================="); log(" = License Overview ="); log(" ================================================="); log(" = PSCafePOS is a POS System for Schools ="); log(" = Copyright (C) 2007 Charles Syperski ="); log(" = ="); log(" = This program is free software; you can ="); log(" = redistribute it and/or modify it under the ="); log(" = terms of the GNU General Public License as ="); log(" = published by the Free Software Foundation; ="); log(" = either version 2 of the License, or any later ="); log(" = version. ="); log(" = ="); log(" = This program is distributed in the hope that ="); log(" = it will be useful, but WITHOUT ANY WARRANTY; ="); log(" = without even the implied warranty of ="); log(" = MERCHANTABILITY or FITNESS FOR A PARTICULAR ="); log(" = PURPOSE. ="); log(" = ="); log(" = See the GNU General Public License for more ="); log(" = details. ="); log(" = ="); log(" = You should have received a copy of the GNU ="); log(" = General Public License along with this ="); log(" = program; if not, write to the ="); log(" = ="); log(" = Free Software Foundation, Inc. ="); log(" = 59 Temple Place, Suite 330 ="); log(" = Boston, MA 02111-1307 USA ="); log(" ================================================="); log(" = If you have any questions of comments please ="); log(" = let us know at http://pscafe.sourceforge.net ="); log(" ================================================="); pause(); File settings; if (blAltSettings) { System.out.println("\n + Alternative path specified at run time:"); System.out.println(" Path: " + strAltPath); settings = new File(strAltPath); } else { settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Checking for existance of settings..."); boolean blGo = false; if (settings.exists() && settings.canRead()) { log("[OK]"); blGo = true; if (forceConfig) { System.out.print("\n + Running Config Wizard (at user request)..."); Process pp = Runtime.getRuntime().exec("java -cp . PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = pp.getErrorStream(); InputStream stdin = pp.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); pp.waitFor(); } } else { log("[FAILED]"); settings = new File("etc" + File.separatorChar + "settings.dbp.firstrun"); System.out.print("\n + Checking if this is the first run... "); if (settings.exists() && settings.canRead()) { log("[FOUND]"); File toFile = new File("etc" + File.separatorChar + "settings.dbp"); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(settings); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } if (toFile.exists() && toFile.canRead()) { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Running Settings Wizard... "); try { Process p = Runtime.getRuntime().exec("java PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = p.getErrorStream(); InputStream stdin = p.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); p.waitFor(); log("[OK]"); if (p.exitValue() == 0) blGo = true; } catch (InterruptedException i) { System.err.println(i.getMessage()); } } catch (Exception ex) { System.err.println(ex.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } else { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); DBSettingsWriter writ = new DBSettingsWriter(); writ.writeFile(new DBSettings(), settings); blGo = true; } } if (blGo) { String cp = "."; try { File classpath = new File("lib"); File[] subFiles = classpath.listFiles(); for (int i = 0; i < subFiles.length; i++) { if (subFiles[i].isFile()) { cp += File.pathSeparatorChar + "lib" + File.separatorChar + subFiles[i].getName() + ""; } } } catch (Exception e) { System.err.println(e.getMessage()); } try { boolean blExecutePOS = false; System.out.print("\n + Checking runtime settings... "); DBSettings info = null; if (settings == null) settings = new File("etc" + File.separatorChar + "settings.dbp"); if (settings.exists() && settings.canRead()) { DBSettingsWriter writ = new DBSettingsWriter(); info = (DBSettings) writ.loadSettingsDB(settings); if (info != null) { blExecutePOS = true; } } if (blExecutePOS) { log("[OK]"); String strSSL = ""; String strSSLDebug = ""; if (info != null) { debug = info.get(DBSettings.MAIN_DEBUG).compareTo("1") == 0; if (debug) log(" * Debug Mode is ON"); else log(" * Debug Mode is OFF"); if (info.get(DBSettings.POS_SSLENABLED).compareTo("1") == 0) { strSSL = "-Djavax.net.ssl.keyStore=" + info.get(DBSettings.POS_SSLKEYSTORE) + " -Djavax.net.ssl.keyStorePassword=pscafe -Djavax.net.ssl.trustStore=" + info.get(DBSettings.POS_SSLTRUSTSTORE) + " -Djavax.net.ssl.trustStorePassword=pscafe"; log(" * Using SSL"); debug(" " + strSSL); if (info.get(DBSettings.POS_SSLDEBUG).compareTo("1") == 0) { strSSLDebug = "-Djavax.net.debug=all"; log(" * SSL Debugging enabled"); debug(" " + strSSLDebug); } } } String strPOSRun = "java -cp " + cp + " " + strSSL + " " + strSSLDebug + " POSDriver " + settings.getPath(); debug(strPOSRun); System.out.print("\n + Running PSCafePOS... "); Process pr = Runtime.getRuntime().exec(strPOSRun); System.out.print("[OK]\n\n"); InputStream stderr = pr.getErrorStream(); InputStream stdin = pr.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); InputStreamReader isre = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); BufferedReader bre = new BufferedReader(isre); String line = null; String lineError = null; log(" ================================================="); log(" = Output from PSCafePOS System ="); log(" ================================================="); while ((line = br.readLine()) != null || (lineError = bre.readLine()) != null) { if (line != null) System.out.println(" [PSCafePOS]" + line); if (lineError != null) System.out.println(" [ERR]" + lineError); } pr.waitFor(); log(" ================================================="); log(" = End output from PSCafePOS System ="); log(" = PSCafePOS has exited ="); log(" ================================================="); } else { log("[Failed]"); } } catch (Exception i) { log(i.getMessage()); i.printStackTrace(); } } } catch (Exception e) { log(e.getMessage()); } }
900,204
0
public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
@Override public void run() { while (true) { StringBuilder buffer = new StringBuilder(128); buffer.append("insert into DOMAIN ( ").append(LS); buffer.append(" DOMAIN_ID, TOP_DOMAIN_ID, DOMAIN_HREF, ").append(LS); buffer.append(" DOMAIN_RANK, DOMAIN_TYPE, DOMAIN_STATUS, ").append(LS); buffer.append(" DOMAIN_ICO_CREATED, DOMAIN_CDATE ").append(LS); buffer.append(") values ( ").append(LS); buffer.append(" null ,null, ?,").append(LS); buffer.append(" 1, 2, 1, ").append(LS); buffer.append(" 0, now() ").append(LS); buffer.append(") ").append(LS); String sqlInsert = buffer.toString(); boolean isAutoCommit = false; int i = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = ConnHelper.getConnection(); conn.setAutoCommit(isAutoCommit); pstmt = conn.prepareStatement(sqlInsert); for (i = 0; i < 10; i++) { String lock = "" + ((int) (Math.random() * 100000000)) % 100; pstmt.setString(1, lock); pstmt.executeUpdate(); } if (!isAutoCommit) conn.commit(); rs = pstmt.executeQuery("select max(DOMAIN_ID) from DOMAIN"); if (rs.next()) { String str = System.currentTimeMillis() + " " + rs.getLong(1); } } catch (Exception e) { try { if (!isAutoCommit) conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(System.out); } String msg = System.currentTimeMillis() + " " + Thread.currentThread().getName() + " - " + i + " " + e.getMessage() + LS; FileIO.writeToFile("D:/DEAD_LOCK.txt", msg, true, "GBK"); } finally { ConnHelper.close(conn, pstmt, rs); } } }
900,205
1
protected File getFile(NameCategory category) throws IOException { File home = new File(System.getProperty("user.dir")); String fileName = String.format("%s.txt", category); File file = new File(home, fileName); if (file.exists()) { return file; } else { URL url = DefaultNameGenerator.class.getResource("/sc/common/" + fileName); if (url == null) { throw new IllegalStateException(String.format("Cannot find resource at %s", fileName)); } else { InputStream in = url.openStream(); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { IOUtils.copy(in, out); } finally { out.close(); } } finally { in.close(); } return file; } } }
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; }
900,206
0
public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); }
public static InputStream getResourceAsStream(String resourceName, Class callingClass) { URL url = getResource(resourceName, callingClass); try { return (url != null) ? url.openStream() : null; } catch (IOException e) { return null; } }
900,207
0
private void bubbleSort() { for (int i = 0; i < testfield.length; i++) { for (int j = 0; j < testfield.length - i - 1; j++) if (testfield[j] > testfield[j + 1]) { short temp = testfield[j]; testfield[j] = testfield[j + 1]; testfield[j + 1] = temp; } } }
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; }
900,208
1
private boolean isReservaOK(String urlAddress, String operationId, String idioma, String codigo_pedido, String merchantId) throws ServletException { StringBuffer buf = new StringBuffer(); try { URL url = new URL(urlAddress + "?Num_operacion=" + operationId + "&Idioma=" + idioma + "&Codigo_pedido=" + codigo_pedido + "&MerchantID=" + merchantId); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { buf.append(str); } in.close(); } catch (IOException e) { throw new ServletException(e); } return buf.indexOf("$*$OKY$*$") != -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(); }
900,209
1
private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } }
public static String encrypt(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes("UTF-8")); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
900,210
1
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); }
public static boolean copyFile(File from, File to) { try { FileChannel fromChannel = new FileInputStream(from).getChannel(); FileChannel toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); fromChannel.close(); toChannel.close(); } catch (IOException e) { log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e); return false; } return true; }
900,211
0
public static void main(String[] args) throws IOException { File fileIn = new File("D:\\zz_c\\study2\\src\\study\\io\\A.java"); InputStream fin = new FileInputStream(fileIn); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(); pout.connect(pin); IoRead i = new IoRead(); i.setIn(pin); File fileOU1 = new File("D:\\zz_c\\study2\\src\\study\\io\\A1.java"); File fileOU2 = new File("D:\\zz_c\\study2\\src\\study\\io\\A2.java"); File fileOU3 = new File("D:\\zz_c\\study2\\src\\study\\io\\A3.java"); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU1))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU2))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU3))); PipedInputStream pin2 = new PipedInputStream(); PipedOutputStream pout2 = new PipedOutputStream(); i.addOut(pout2); pout2.connect(pin2); i.start(); int read; try { read = fin.read(); while (read != -1) { pout.write(read); read = fin.read(); } fin.close(); pout.close(); } catch (IOException e) { e.printStackTrace(); } int c = pin2.read(); while (c != -1) { System.out.print((char) c); c = pin2.read(); } pin2.close(); }
public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); }
900,212
0
public static String md5Encrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] md5hash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } md5hash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < md5hash.length; i++) { if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
900,213
0
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
protected static void copyFile(File from, File to) throws IOException { if (!from.isFile() || !to.isFile()) { throw new IOException("Both parameters must be files. from is " + from.isFile() + ", to is " + to.isFile()); } FileChannel in = (new FileInputStream(from)).getChannel(); FileChannel out = (new FileOutputStream(to)).getChannel(); in.transferTo(0, from.length(), out); in.close(); out.close(); }
900,214
1
private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } }
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
900,215
1
protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { InputStream is = servletConfig.getServletContext().getResourceAsStream(pathInfo); if (is == null) { throw new ServletException("Static resource " + pathInfo + " is not available"); } try { int ind = pathInfo.lastIndexOf("."); if (ind != -1 && ind < pathInfo.length()) { String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1)); if (type != null) { response.setContentType(type); } } ServletOutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); } catch (IOException ex) { throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream"); } }
public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException { if (!generatedOutputDirectory.exists()) { generatedOutputDirectory.createFolder(); } if (outputDirectory.exists()) { outputDirectory.createFolder(); } ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/service/xdoc/resources.zip"), outputDirectory); for (Library library : libraryModels) { String libraryName = library.getName(); String libraryLocation = library.getLocation(); generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder(); try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName); FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.xml"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } for (Component component : library.getComponents()) { String componentName = component.getName(); System.out.println("Generating " + libraryName + ":" + componentName + "..."); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("libraryName", libraryName); parameters.put("componentName", componentName); String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters); Writer out = null; try { FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true)); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); Resource specificationLocation = component.getSpecificationLocation(); if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) { File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI()); FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource"); if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) { File[] files = srcResourcesDirectory.listFiles(); if (files != null) { for (File resource : files) { if (resource.isFile() && !resource.isHidden()) { FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName()); resourceFileObject.createFile(); InputStream inResource = null; OutputStream outResource = null; try { inResource = new FileInputStream(resource); outResource = resourceFileObject.getContent().getOutputStream(); IOUtils.copy(inResource, outResource); } finally { IOUtils.closeQuietly(inResource); IOUtils.closeQuietly(outResource); } } } } } } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } } { Writer out = null; try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl")); FileObject index = generatedOutputDirectory.resolveFile("index.xml"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } }
900,216
0
@Test public void test_lookupType_FullSearch_TwoWords() throws Exception { URL url = new URL(baseUrl + "/lookupType/deep+core"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":11395,\"itemCategoryID\":16,\"name\":\"Deep Core Mining\",\"icon\":\"50_11\"},{\"itemTypeID\":12108,\"itemCategoryID\":7,\"name\":\"Deep Core Mining Laser I\",\"icon\":\"35_01\",\"metaLevel\":0},{\"itemTypeID\":12109,\"itemCategoryID\":9,\"name\":\"Deep Core Mining Laser I Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":18068,\"itemCategoryID\":7,\"name\":\"Modulated Deep Core Miner II\",\"icon\":\"35_01\",\"metaLevel\":5},{\"itemTypeID\":18069,\"itemCategoryID\":9,\"name\":\"Modulated Deep Core Miner II Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":24305,\"itemCategoryID\":7,\"name\":\"Modulated Deep Core Strip Miner II\",\"icon\":\"49_05\",\"metaLevel\":5},{\"itemTypeID\":24306,\"itemCategoryID\":9,\"name\":\"Modulated Deep Core Strip Miner II Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":28748,\"itemCategoryID\":7,\"name\":\"ORE Deep Core Mining Laser\",\"icon\":\"35_01\",\"metaLevel\":6}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); }
@Override public String encryptPassword(String password) throws JetspeedSecurityException { if (securePasswords == false) { return password; } if (password == null) { return null; } try { if ("SHA-512".equals(passwordsAlgorithm)) { password = password + JetspeedResources.getString("aipo.encrypt_key"); MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); md.reset(); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < hash.length; i++) { sb.append(Integer.toHexString((hash[i] >> 4) & 0x0F)); sb.append(Integer.toHexString(hash[i] & 0x0F)); } return sb.toString(); } else { MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); byte[] digest = md.digest(password.getBytes(ALEipConstants.DEF_CONTENT_ENCODING)); ByteArrayOutputStream bas = new ByteArrayOutputStream(digest.length + digest.length / 3 + 1); OutputStream encodedStream = MimeUtility.encode(bas, "base64"); encodedStream.write(digest); encodedStream.flush(); encodedStream.close(); return bas.toString(); } } catch (Exception e) { logger.error("Unable to encrypt password." + e.getMessage(), e); return null; } }
900,217
0
protected N save(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); rs = pstmt.getGeneratedKeys(); return (N) rs.getObject(1); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(rs, pstmt, conn); } }
protected String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception ex) { throw new TiiraException(ex); } }
900,218
0
public static void testString(String string, String expected) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(string.getBytes(), 0, string.length()); String result = toString(md.digest()); System.out.println(expected); System.out.println(result); if (!expected.equals(result)) System.out.println("NOT EQUAL!"); } catch (Exception x) { x.printStackTrace(); } }
private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); }
900,219
0
public static String md5(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException { StringBuffer result = new StringBuffer(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes("utf-8")); byte[] digest = md.digest(); for (byte b : digest) { result.append(String.format("%02X ", b & 0xff)); } return result.toString(); }
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { try { if (vtf == null) { LOG.debug("Serializing from database"); existDocument.stream(out); } else { LOG.debug("Serializing from buffer"); InputStream is = vtf.getByteStream(); IOUtils.copy(is, out); out.flush(); IOUtils.closeQuietly(is); vtf.delete(); vtf = null; } } catch (PermissionDeniedException e) { LOG.debug(e.getMessage()); throw new NotAuthorizedException(this); } finally { IOUtils.closeQuietly(out); } }
900,220
0
public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) { boolean inserto = false; try { stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )"); stm.executeUpdate(); conexion.commit(); inserto = true; } catch (SQLException e) { System.out.println("error al insertar registro en la tabla clientes general " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return inserto = false; } return inserto; }
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
900,221
0
public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
public static int executeNoQuery(String strStatement) throws SQLException { MyDBConnection myc = new MyDBConnection(); myc.init(); Statement statement = myc.getMyConnection().createStatement(); try { int rows = statement.executeUpdate(strStatement); myc.myConnection.commit(); return rows; } catch (SQLException e) { myc.myConnection.rollback(); throw new SQLException("rollback e close effettuato dopo " + e.getMessage()); } finally { myc.close(); } }
900,222
1
public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) { final byte[] resourceBytes = readResource(owningClass, resourceName); final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes); final File destinationFile = new File(destinationDir, resourceName); final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(destinationFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } }
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!"); }
900,223
0
private void checkSites() { Log.d(LOG_TAG, "Updating sites: " + sitesToCheck.keySet().toString()); for (Map.Entry<Site, Item> entry : sitesToCheck.entrySet()) { final Site site = entry.getKey(); final Item oldItem = entry.getValue(); try { final HttpGet req = new HttpGet(site.getUrl().toURI()); req.addHeader("Cache-Control", "no-cache"); req.addHeader("Pragma", "no-cache"); if (oldItem != null) { final Date lastModified = oldItem.getTimestamp(); if (lastModified != null) { req.addHeader("If-Modified-Since", Utils.formatRFC822Date(lastModified)); } } final HttpResponse response = httpClient.execute(req); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final FeedHandler handler = site.getHandler().newInstance(); final InputStream in = response.getEntity().getContent(); Xml.parse(in, site.getEncoding(), handler); in.close(); notify(site, handler.getCurrentItem()); } else if (response.getStatusLine().getStatusCode() != 304) { Log.e(LOG_TAG, "HTTP request for " + site.name() + " failed: " + response.getStatusLine().toString()); } } catch (Throwable e) { Log.e(LOG_TAG, e.getMessage(), e); } } }
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; }
900,224
0
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
@Override public DaeScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { NullArgumentException.check(url); boolean baseURLWasNull = setBaseURLFromModelURL(url); DaeScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); }
900,225
0
public void mousePressed(MouseEvent e) { bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(bannerURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); HttpHost host = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); String targetURL = host.toURI() + request.getURI(); DesktopUtil.browseAndWarn(targetURL, bannerLbl); EntityUtils.consume(entity); } catch (Exception ex) { NotifyUtil.error("Banner Error", "Could not open the default web browser.", ex, false); } finally { method.abort(); } bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); }
public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
900,226
1
private static Vector<String> getIgnoreList() { try { URL url = DeclarationTranslation.class.getClassLoader().getResource("ignorelist"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); Vector<String> ret = new Vector<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { ret.add(line); } return ret; } catch (Exception e) { return null; } }
private boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("hyk-proxy"); } catch (Exception e) { } return false; }
900,227
1
public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } }
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(); } }
900,228
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(); } } }
private String read(URL url) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer text = new StringBuffer(); String line; while ((line = in.readLine()) != null) { text.append(line); } return text.toString(); } finally { in.close(); } }
900,229
0
public RFC1345List(URL url) { if (url == null) return; try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); final String linePattern = " XX??????? HHHH X"; String line; mnemos = new HashMap(); nextline: while ((line = br.readLine()) != null) { if (line.length() < 9) continue nextline; if (line.charAt(7) == ' ' || line.charAt(8) != ' ') { line = line.substring(0, 8) + " " + line.substring(8); } if (line.length() < linePattern.length()) continue nextline; for (int i = 0; i < linePattern.length(); i++) { char c = line.charAt(i); switch(linePattern.charAt(i)) { case ' ': if (c != ' ') continue nextline; break; case 'X': if (c == ' ') continue nextline; break; case '?': break; case 'H': if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) ; else continue nextline; break; default: throw new RuntimeException("Pattern broken!"); } } char c = (char) Integer.parseInt(line.substring(16, 20), 16); String mnemo = line.substring(1, 16).trim(); if (mnemo.length() < 2) throw new RuntimeException(); mnemos.put(mnemo, new Character(c)); } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } }
private File getTestFile() { final URL url = TestCrueLOG.class.getResource(FICHIER_TEST_XML); final File ctfaFile = new File(createTempDir(), "resultat.rtfa.xml"); try { CtuluLibFile.copyStream(url.openStream(), new FileOutputStream(ctfaFile), true, true); } catch (Exception e) { e.printStackTrace(); fail(); } return ctfaFile; }
900,230
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; }
public void xtest7() throws Exception { System.out.println("Lowagie"); FileInputStream inputStream = new FileInputStream("C:/Temp/arquivo.pdf"); PDFBoxManager manager = new PDFBoxManager(); InputStream[] images = manager.toImage(inputStream, "jpeg"); int count = 0; for (InputStream image : images) { FileOutputStream outputStream = new FileOutputStream("C:/Temp/arquivo_" + count + ".jpg"); IOUtils.copy(image, outputStream); count++; outputStream.close(); } inputStream.close(); }
900,231
0
private static InputStream connect(final String url) throws IOException { InputStream in = null; try { final URLConnection conn = new URL(url).openConnection(); conn.setConnectTimeout(YahooGeocoding.connectTimeOut); conn.setReadTimeout(YahooGeocoding.readTimeOut); conn.setRequestProperty("User-Agent", YahooGeocoding.USER_AGENT); in = conn.getInputStream(); return in; } catch (final IOException e) { Util.d("problems connecting to geonames url " + url + "Exception:" + e); } return in; }
public File createReadmeFile(File dir, MavenProject mavenProject) throws IOException { InputStream is = getClass().getResourceAsStream("README.template"); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw); String content = sw.getBuffer().toString(); content = StringUtils.replace(content, "{project_name}", mavenProject.getArtifactId()); File readme = new File(dir, "README.TXT"); FileUtils.writeStringToFile(readme, content); return readme; }
900,232
0
public String setEncryptedPassword(String rawPassword) { String out = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(rawPassword.getBytes()); byte raw[] = md.digest(); out = new String(); for (int x = 0; x < raw.length; x++) { String hex2 = Integer.toHexString((int) raw[x] & 0xFF); if (1 == hex2.length()) { hex2 = "0" + hex2; } out += hex2; int a = 1; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return out; }
public static URL[] getURLsForAllJars(URL url, File tmpDir) { FileInputStream fin = null; InputStream in = null; ZipInputStream zin = null; try { ArrayList array = new ArrayList(); in = url.openStream(); String fileName = url.getFile(); int index = fileName.lastIndexOf('/'); if (index != -1) { fileName = fileName.substring(index + 1); } final File f = createTempFile(fileName, in, tmpDir); fin = (FileInputStream) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream(f); } }); array.add(f.toURL()); zin = new ZipInputStream(fin); ZipEntry entry; String entryName; while ((entry = zin.getNextEntry()) != null) { entryName = entry.getName(); if ((entryName != null) && entryName.toLowerCase().startsWith("lib/") && entryName.toLowerCase().endsWith(".jar")) { String suffix = entryName.substring(4); File f2 = createTempFile(suffix, zin, tmpDir); array.add(f2.toURL()); } } return (URL[]) array.toArray(new URL[array.size()]); } catch (Exception e) { throw new RuntimeException(e); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (zin != null) { try { zin.close(); } catch (IOException e) { } } } }
900,233
1
public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } }
public void filter(File source, File destination, MNamespace mNamespace) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(source)); BufferedWriter writer = new BufferedWriter(new FileWriter(destination)); int line = 0; int column = 0; Stack parseStateStack = new Stack(); parseStateStack.push(new ParseState(mNamespace)); for (Iterator i = codePieces.iterator(); i.hasNext(); ) { NamedCodePiece cp = (NamedCodePiece) i.next(); while (line < cp.getStartLine()) { line++; column = 0; writer.write(reader.readLine()); writer.newLine(); } while (column < cp.getStartPosition()) { writer.write(reader.read()); column++; } cp.write(writer, parseStateStack, column); while (line < cp.getEndLine()) { line++; column = 0; reader.readLine(); } while (column < cp.getEndPosition()) { column++; reader.read(); } } String data; while ((data = reader.readLine()) != null) { writer.write(data); writer.newLine(); } reader.close(); writer.close(); }
900,234
1
public Object downloadFile(File destinationFile, URL[] urls, DownloadListener listener, Object checksum, long length, PRIORITY priority) throws DownloadException { URL url = urls[0]; if (!url.getProtocol().equalsIgnoreCase("http")) { throw new DownloadException(" Only HTTP is supported in this version "); } if (!destinationFile.exists()) { try { destinationFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); throw new DownloadException("Unable to download from URL : " + url.toString()); } } HeadMethod head = new HeadMethod(url.toString()); HttpClient httpClient = new HttpClient(); try { httpClient.executeMethod(head); Header[] headers = head.getResponseHeaders(); for (Header header : headers) { System.out.println(header); } Header header = head.getResponseHeader("Content-Length"); Object contentLength = header.getValue(); Long fileLength = Long.parseLong(contentLength.toString()); System.out.println(length + " : " + fileLength); GetMethod get = new GetMethod(url.toString()); httpClient.executeMethod(get); InputStream ins = get.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(destinationFile); IOUtils.copy(ins, fos); System.out.println(" DOWNLOADED FILE"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
protected void writeGZippedBytes(byte array[], TupleOutput out) { if (array == null || array.length == 0) { out.writeBoolean(false); writeBytes(array, out); return; } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); GZIPOutputStream gzout = new GZIPOutputStream(baos); ByteArrayInputStream bais = new ByteArrayInputStream(array); IOUtils.copyTo(bais, gzout); gzout.finish(); gzout.close(); bais.close(); byte compressed[] = baos.toByteArray(); if (compressed.length < array.length) { out.writeBoolean(true); writeBytes(compressed, out); } else { out.writeBoolean(false); writeBytes(array, out); } } catch (IOException err) { throw new RuntimeException(err); } }
900,235
1
private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
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(); } }
900,236
0
public static byte[] resolveRef(String url) throws MalformedURLException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); URL addressurl = new URL(url); InputStream in = addressurl.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer, 0, bufferSize)) != -1) { out.write(buffer, 0, bytesRead); out.flush(); } return out.toByteArray(); }
public byte[] getByteCode() throws IOException { InputStream in = null; ByteArrayOutputStream buf = new ByteArrayOutputStream(2048); try { in = url.openStream(); int b = in.read(); while (b != -1) { buf.write(b); b = in.read(); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } return buf.toByteArray(); }
900,237
1
public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HashMap services = configContext.getAxisConfiguration().getServices(); String filePart = req.getRequestURL().toString(); String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length()); if ((services != null) && !services.isEmpty()) { Iterator i = services.values().iterator(); while (i.hasNext()) { AxisService service = (AxisService) i.next(); InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema); if (stream != null) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); IOUtils.copy(stream, out, true); return; } } } }
public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) { throw new IOException("FileCopy: no such source file: " + from_file.getPath()); } if (!from_file.isFile()) { throw new IOException("FileCopy: can't copy directory: " + from_file.getPath()); } if (!from_file.canRead()) { throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath()); } if (to_file.isDirectory()) { to_file = new File(to_file, from_file.getName()); } if (to_file.exists()) { if (!to_file.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath()); } int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { throw new IOException("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent(); if (parent == null) { parent = Globals.getDefaultPath(); } 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(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
900,238
1
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
@Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; }
900,239
0
public void testServletTesterClient() throws Exception { String base_url = tester.createSocketConnector(true); URL url = new URL(base_url + "/context/hello/info"); String result = IO.toString(url.openStream()); assertEquals("<h1>Hello Servlet</h1>", result); }
public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } }
900,240
1
public String getHash(String type, String text, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance(type); byte[] hash = new byte[md.getDigestLength()]; if (!salt.isEmpty()) { md.update(salt.getBytes("iso-8859-1"), 0, salt.length()); } md.update(text.getBytes("iso-8859-1"), 0, text.length()); hash = md.digest(); return convertToHex(hash); }
public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); }
900,241
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!"); }
protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); }
900,242
1
private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
private static void loadFromZip() { InputStream in = Resources.class.getResourceAsStream("data.zip"); if (in == null) { return; } ZipInputStream zipIn = new ZipInputStream(in); try { while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String entryName = entry.getName(); if (!entryName.startsWith("/")) { entryName = "/" + entryName; } ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(zipIn, out); zipIn.closeEntry(); FILES.put(entryName, out.toByteArray()); } zipIn.close(); } catch (IOException e) { e.printStackTrace(); } }
900,243
0
public File getFile(String file) { DirProperties dp; List files = new ArrayList(); for (int i = 0; i < locs.size(); i++) { dp = (DirProperties) locs.get(i); if (dp.isReadable()) { File g = new File(dp.getLocation() + slash() + file); if (g.exists()) files.add(g); } } if (files.size() == 0) { throw new UnsupportedOperationException("at least one DirProperty should get 'read=true'"); } else if (files.size() == 1) { return (File) files.get(0); } else { File fromFile = (File) files.get(files.size() - 2); File toFile = (File) files.get(files.size() - 1); byte reading[] = new byte[2024]; try { FileInputStream stream = new FileInputStream(fromFile); FileOutputStream outStr = new FileOutputStream(toFile); while (stream.read(reading) != -1) { outStr.write(reading); } } catch (FileNotFoundException ex) { getLogger().severe("FileNotFound: while copying from " + fromFile + " to " + toFile); } catch (IOException ex) { getLogger().severe("IOException: while copying from " + fromFile + " to " + toFile); } return toFile; } }
public void startImport(ActionEvent evt) { final PsiExchange psiExchange = PsiExchangeFactory.createPsiExchange(IntactContext.getCurrentInstance().getSpringContext()); for (final URL url : urlsToImport) { try { if (log.isInfoEnabled()) log.info("Importing: " + url); psiExchange.importIntoIntact(url.openStream()); } catch (IOException e) { handleException(e); return; } } addInfoMessage("File successfully imported", Arrays.asList(urlsToImport).toString()); }
900,244
0
public static void assertEquals(String xmlpath, Object actualObject) throws Exception { InputStreamReader isr; try { isr = new FileReader(xmlpath); } catch (FileNotFoundException e) { URL url = AssertHelper.class.getClassLoader().getResource(xmlpath); if (null != url) { try { isr = new InputStreamReader(url.openStream()); } catch (Exception e1) { throw new AssertionFailedError("Unable to find output xml : " + xmlpath); } } else { throw new AssertionFailedError("Could not read output xml : " + xmlpath); } } DOMParser parser = new DOMParser(); parser.parse(new InputSource(isr)); Document document = parser.getDocument(); try { assertEqual(document.getDocumentElement(), actualObject); } catch (AssertionFailedError e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } AssertionFailedError a = new AssertionFailedError(sbf.toString()); a.setStackTrace(e.getStackTrace()); throw a; } catch (Exception e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } Exception ex = new Exception(sbf.toString()); ex.setStackTrace(e.getStackTrace()); throw ex; } }
public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
900,245
1
static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } }
protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
900,246
0
private void createProperty(String objectID, String value, String propertyID, Long userID) throws JspTagException { ClassProperty classProperty = new ClassProperty(new Long(propertyID)); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(new Long(propertyID), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } }
public static void replaceAll(File file, String substitute, String substituteReplacement) throws IOException { log.debug("Replace " + substitute + " by " + substituteReplacement); Pattern pattern = Pattern.compile(substitute); FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); Charset charset = Charset.forName("ISO-8859-15"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cb = decoder.decode(bb); Matcher matcher = pattern.matcher(cb); String outString = matcher.replaceAll(substituteReplacement); log.debug(outString); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); PrintStream ps = new PrintStream(fos); ps.print(outString); ps.close(); fos.close(); }
900,247
0
public String getDataAsString(String url) throws RuntimeException { try { String responseBody = ""; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStreamReader re = new InputStreamReader(urlc.getInputStream()); BufferedReader rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += "\n"; line = null; } rd.close(); re.close(); return responseBody; } catch (Exception e) { throw new RuntimeException(e); } }
TreeMap<Integer, Integer> initProperties(URL propurl) { String zoneFileName = null; String costFileName = null; String homesFileName = null; String jobsFileName = null; Properties props = new Properties(); try { props.loadFromXML(propurl.openStream()); zoneFileName = props.getProperty("zoneFileName"); costFileName = props.getProperty("costFileName"); homesFileName = props.getProperty("homesFileName"); jobsFileName = props.getProperty("jobsFileName"); maxiter = Integer.parseInt(props.getProperty("maxiter")); mu = Double.parseDouble(props.getProperty("mu")); theta = Double.parseDouble(props.getProperty("theta")); threshold1 = Double.parseDouble(props.getProperty("threshold1")); threshold2 = Double.parseDouble(props.getProperty("threshold2")); verbose = Boolean.parseBoolean(props.getProperty("verbose")); } catch (Exception xc) { xc.printStackTrace(); System.exit(-1); } HashSet<Integer> zoneids = SomeIO.readZoneIDs(zoneFileName); numZ = zoneids.size(); if (verbose) { System.out.println("Data:"); System.out.println(" . #zones:" + numZ); } int idx = 0; TreeMap<Integer, Integer> zonemap = new TreeMap<Integer, Integer>(); for (Integer id : zoneids) zonemap.put(id, idx++); cij = SomeIO.readMatrix(costFileName, numZ, numZ); for (int i = 0; i < numZ; i++) { double mincij = Double.POSITIVE_INFINITY; for (int j = 0; j < numZ; j++) { double v = cij.get(i, j); if ((v < mincij) && (v > 0.0)) mincij = v; } if (cij.get(i, i) == 0.0) cij.set(i, i, mincij); } setupECij(); double meanCost = 0.0; double stdCost = 0.0; for (int i = 0; i < numZ; i++) { for (int j = 0; j < numZ; j++) { double v = cij.get(i, j); meanCost += v; stdCost += v * v; } } meanCost = meanCost / (numZ * numZ); stdCost = stdCost / (numZ * numZ) - meanCost * meanCost; if (verbose) System.out.println(" . Travel costs mean=" + meanCost + " std.dev.= " + Math.sqrt(stdCost)); P = SomeIO.readZoneAttribute(numZ, homesFileName, zonemap); J = SomeIO.readZoneAttribute(numZ, jobsFileName, zonemap); double maxpj = 0.0; double sp = 0.0; double sj = 0.0; for (int i = 0; i < numZ; i++) { sp += P[i]; sj += J[i]; if (P[i] > maxpj) maxpj = P[i]; if (J[i] > maxpj) maxpj = J[i]; } if (Math.abs(sp - sj) > 1.0) { System.err.println("Error: #jobs(" + sj + ")!= #homes(" + sp + ")"); System.exit(-1); } N = sp; if (verbose) System.out.println(" . Trip tables: #jobs=#homes= " + N); return zonemap; }
900,248
1
private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractSRLParser labeler = null; AbstractDecoder[] decoder = null; if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); labeler = new SRLParser(flag, s_featureXml); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); labeler = new SRLParser(flag, t_xml, s_lexiconFiles); } else if (flag == SRLParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train boost"); decoder = new AbstractDecoder[m_model.length]; for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]); labeler = new SRLParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true); DepTree tree; int n; labeler.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { labeler.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- labeling: " + n); if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("- labeling"); labeler.saveTags(s_lexiconFiles); t_xml = labeler.getSRLFtrXml(); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) { a_yx = labeler.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); for (String lexicaFile : s_lexiconFiles) { zout.putArchiveEntry(new JarArchiveEntry(lexicaFile)); IOUtils.copy(new FileInputStream(lexicaFile), zout); zout.closeArchiveEntry(); } if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap(); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_FULL_PREFIX) + Constants.SERVLET_FULL_PREFIX.length() + 1); boolean notScale = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_NOT_SCALE)); ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { String mimetype = fedoraAccess.getMimeTypeForStream(uuid, FedoraUtils.IMG_FULL_STREAM); if (mimetype == null) { mimetype = "image/jpeg"; } ImageMimeType loadFromMimeType = ImageMimeType.loadFromMimeType(mimetype); if (loadFromMimeType == ImageMimeType.JPEG || loadFromMimeType == ImageMimeType.PNG) { StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_FULL/content"); InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to close stream.", e); } finally { is = null; } } } } else { Image rawImg = KrameriusImageSupport.readImage(uuid, FedoraUtils.IMG_FULL_STREAM, this.fedoraAccess, 0, loadFromMimeType); BufferedImage scaled = null; if (!notScale) { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 1250, 1000); } else { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 2500, 2000); } KrameriusImageSupport.writeImageToStream(scaled, "JPG", os); resp.setContentType(ImageMimeType.JPEG.getValue()); resp.setStatus(HttpURLConnection.HTTP_OK); } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } catch (XPathExpressionException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to create XPath expression.", e); } finally { os.flush(); } } }
900,249
0
private byte[] cacheInputStream(URL url) throws IOException { InputStream ins = url.openStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[256]; while (true) { int n = ins.read(buf); if (n == -1) break; bout.write(buf, 0, n); } return bout.toByteArray(); }
protected void loadUrl(URL url) throws BuildException { Properties props = new Properties(); log("Loading " + url, Project.MSG_VERBOSE); try { InputStream is = url.openStream(); try { loadProperties(props, is, url.getFile().endsWith(".xml")); } finally { if (is != null) { is.close(); } } addProperties(props); } catch (IOException ex) { throw new BuildException(ex, getLocation()); } }
900,250
0
protected static DynamicJasperDesign generateJasperDesign(DynamicReport dr) throws CoreException { DynamicJasperDesign jd = null; try { if (dr.getTemplateFileName() != null) { log.info("loading template file: " + dr.getTemplateFileName()); log.info("Attemping to find the file directly in the file system..."); File file = new File(dr.getTemplateFileName()); if (file.exists()) { JasperDesign jdesign = JRXmlLoader.load(file); jd = DJJRDesignHelper.downCast(jdesign, dr); } else { log.info("Not found: Attemping to find the file in the classpath..."); URL url = DynamicJasperHelper.class.getClassLoader().getResource(dr.getTemplateFileName()); JasperDesign jdesign = JRXmlLoader.load(url.openStream()); jd = DJJRDesignHelper.downCast(jdesign, dr); } JasperDesignHelper.populateReportOptionsFromDesign(jd, dr); } else { jd = DJJRDesignHelper.getNewDesign(dr); } registerParameters(jd, dr); } catch (JRException e) { throw new CoreException(e.getMessage(), e); } catch (IOException e) { throw new CoreException(e.getMessage(), e); } return jd; }
public void testReleaseOnEntityWriteTo() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); assertEquals(1, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
900,251
1
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } }
public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
900,252
1
public static synchronized String getSequenceNumber(String SequenceName) { String result = "0"; Connection conn = null; Statement ps = null; ResultSet rs = null; try { conn = TPCW_Database.getConnection(); conn.setAutoCommit(false); String sql = "select num from sequence where name='" + SequenceName + "'"; ps = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = ps.executeQuery(sql); long num = 0; while (rs.next()) { num = rs.getLong(1); result = new Long(num).toString(); } num++; sql = "update sequence set num=" + num + " where name='" + SequenceName + "'"; int res = ps.executeUpdate(sql); if (res == 1) { conn.commit(); } else conn.rollback(); } catch (Exception e) { System.out.println("Error Happens when trying to obtain the senquence number"); e.printStackTrace(); } finally { try { if (conn != null) conn.close(); if (rs != null) rs.close(); if (ps != null) ps.close(); } catch (SQLException se) { se.printStackTrace(); } } return result; }
public void modify(String strName, String strNewPass) { String str = "update jb_user set V_PASSWORD =? where V_USERNAME =?"; Connection con = null; PreparedStatement pstmt = null; try { con = DbForumFactory.getConnection(); con.setAutoCommit(false); pstmt = con.prepareStatement(str); pstmt.setString(1, SecurityUtil.md5ByHex(strNewPass)); pstmt.setString(2, strName); pstmt.executeUpdate(); con.commit(); } catch (Exception e) { e.printStackTrace(); try { con.rollback(); } catch (SQLException e1) { } } finally { try { DbForumFactory.closeDB(null, pstmt, null, con); } catch (Exception e) { } } }
900,253
0
public FileInputStream execute() { FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); String pdfPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf"); try { FileOutputStream outputStream = new FileOutputStream(pdfPath + "/driveTogether.pdf"); PdfWriter writer = PdfWriter.getInstance(doc, outputStream); doc.open(); String pfad = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf/template.pdf"); logger.info("Loading PDF-Template: " + pfad); PdfReader reader = new PdfReader(pfad); PdfImportedPage page = writer.getImportedPage(reader, 1); PdfContentByte cb = writer.getDirectContent(); cb.addTemplate(page, 0, 0); doHeader(); doParagraph(trip, forUser); doc.close(); fis = new FileInputStream(pdfPath + "/driveTogether.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fis; }
public static String generateHash(String value) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(value.getBytes()); } catch (NoSuchAlgorithmException e) { log.error("Could not find the requested hash method: " + e.getMessage()); } byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); }
900,254
0
public static void main(String args[]) { if (args.length < 1) { printUsage(); } URL url; BufferedReader in = null; try { url = new URL(args[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if (responseCode == 200) { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } else { System.out.println("Response code " + responseCode + " means there was an error reading url " + args[0]); } } catch (IOException e) { System.err.println("IOException attempting to read url " + args[0]); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception ignore) { } } } }
public void removerQuestaoMultiplaEscolha(QuestaoMultiplaEscolha multiplaEscolha) throws ClassNotFoundException, SQLException { this.criaConexao(false); String sql = "DELETE FROM \"Disciplina\" " + " WHERE ID_Disciplina = ? )"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.executeUpdate(); connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
900,255
1
public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File(destination); if (destinationFile.exists()) { destinationFile.delete(); } sourceStream = new BufferedInputStream(new FileInputStream(source)); destStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); int readByte; while ((readByte = sourceStream.read()) > 0) { destStream.write(readByte); } Object[] arg = { destinationFile.getName() }; String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg); LOG.fine(msg); } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } finally { try { if (destStream != null) { destStream.close(); } if (sourceStream != null) { sourceStream.close(); } } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } } }
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
900,256
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(); } } }
protected HttpResponseImpl makeRequest(final HttpMethod m, final String requestId) { try { HttpResponseImpl ri = new HttpResponseImpl(); ri.setRequestMethod(m); ri.setResponseCode(_client.executeMethod(m)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(m.getResponseBodyAsStream(), bos); ri.setResponseBody(bos.toByteArray()); notifyOfRequestSuccess(requestId, m, ri); return ri; } catch (HttpException ex) { notifyOfRequestFailure(requestId, m, ex); } catch (IOException ex) { notifyOfRequestFailure(requestId, m, ex); } return null; }
900,257
0
private void loadDBpediaOntology() { try { URL url = new URL("http://downloads.dbpedia.org/3.6/dbpedia_3.6.owl.bz2"); InputStream is = new BufferedInputStream(url.openStream()); CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); dbPediaOntology = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(in); reasoner = PelletReasonerFactory.getInstance().createNonBufferingReasoner(dbPediaOntology); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (CompressorException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") protected void processDownloadAction(HttpServletRequest request, HttpServletResponse response) throws Exception { File transformationFile = new File(xslBase, "file-info.xsl"); HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); DataSourceIf dataSource = new NullSource(); Document fileInfoDoc = XmlUtils.getEmptyDOM(); DOMResult result = new DOMResult(fileInfoDoc); transformer.transform((Source) dataSource, result); Element documentElement = fileInfoDoc.getDocumentElement(); if (documentElement.getLocalName().equals("null")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } InputStream is = null; try { XPath xpath = XPathFactory.newInstance().newXPath(); String sourceType = XPathUtils.getStringValue(xpath, "source-type", documentElement, null); String location = XPathUtils.getStringValue(xpath, "location", documentElement, null); String fileName = XPathUtils.getStringValue(xpath, "file-name", documentElement, null); String mimeType = XPathUtils.getStringValue(xpath, "mime-type", documentElement, null); String encoding = XPathUtils.getStringValue(xpath, "encoding", documentElement, null); if (StringUtils.equals(sourceType, "cifsSource")) { String domain = XPathUtils.getStringValue(xpath, "domain", documentElement, null); String userName = XPathUtils.getStringValue(xpath, "username", documentElement, null); String password = XPathUtils.getStringValue(xpath, "password", documentElement, null); URI uri = new URI(location); if (StringUtils.isNotBlank(userName)) { String userInfo = ""; if (StringUtils.isNotBlank(domain)) { userInfo = userInfo + domain + ";"; } userInfo = userInfo + userName; if (StringUtils.isNotBlank(password)) { userInfo = userInfo + ":" + password; } uri = new URI(uri.getScheme(), userInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } SmbFile smbFile = new SmbFile(uri.toURL()); is = new SmbFileInputStream(smbFile); } else if (StringUtils.equals(sourceType, "localFileSystemSource")) { File file = new File(location); is = new FileInputStream(file); } else { logger.error("Source type \"" + ((sourceType != null) ? sourceType : "") + "\" not supported"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (StringUtils.isBlank(mimeType) && StringUtils.isBlank(encoding)) { response.setContentType(Definitions.MIMETYPE_BINARY); } else if (StringUtils.isBlank(encoding)) { response.setContentType(mimeType); } else { response.setContentType(mimeType + ";charset=" + encoding); } if (request.getParameterMap().containsKey(Definitions.REQUEST_PARAMNAME_DOWNLOAD)) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); } IOUtils.copy(new BufferedInputStream(is), response.getOutputStream()); } finally { if (is != null) { is.close(); } } }
900,258
0
@SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } }
public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
900,259
1
private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(RuleParameter.MODIFICATION_EXCLUDES_DEFAULT.getValue()); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true, new AttackMailHandler()); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(RuleParameter.RESPONSE_MODIFICATIONS_DEFAULT.getValue()); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List<Pattern> tmpPatternsToExcludeCompleteTag = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeCompleteScript = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteTag = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteScript = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList<Integer[]>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList<Integer[]>(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); }
public void testRenderRules() { try { MappingManager manager = new MappingManager(); OWLOntologyManager omanager = OWLManager.createOWLOntologyManager(); OWLOntology srcOntology; OWLOntology targetOntology; manager.loadMapping(rulesDoc.toURL()); srcOntology = omanager.loadOntologyFromPhysicalURI(srcURI); targetOntology = omanager.loadOntologyFromPhysicalURI(targetURI); manager.setSourceOntology(srcOntology); manager.setTargetOntology(targetOntology); Graph srcGraph = manager.getSourceGraph(); Graph targetGraph = manager.getTargetGraph(); System.out.println("Starting to render..."); FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(srcGraph); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); System.out.println("View updated with graph..."); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); System.out.println("Finished writing"); writer.close(); System.out.println("Finished render... XML is:"); System.out.println(writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
900,260
1
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
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()); } }
900,261
1
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 { } }
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
900,262
0
@Override public ImageData getImageData(URL url) { InputStream in = null; try { URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", "Tahiti/Alpha5x"); conn.setRequestProperty("agent-system", "aglets"); conn.setAllowUserInteraction(true); conn.connect(); in = conn.getInputStream(); String type = conn.getContentType(); int len = conn.getContentLength(); if (len < 0) { len = in.available(); } byte[] b = new byte[len]; int off = 0; int n = 0; while (n < len) { int count = in.read(b, off + n, len - n); if (count < 0) { throw new java.io.EOFException(); } n += count; } in.close(); return new AgletImageData(url, b, type); } catch (Exception ex) { ex.printStackTrace(); return null; } }
private void startOpening(final URL url) { final WebAccessor wa = this; openerThread = new Thread() { public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } } }; openerThread.start(); }
900,263
0
public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } }
public InputStream getResourceAsStream(String path) { try { URL url = getResource(path); if (url != null) { return url.openStream(); } else { return null; } } catch (IOException ioe) { return null; } }
900,264
0
public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) { boolean inserto = false; try { stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )"); stm.executeUpdate(); conexion.commit(); inserto = true; } catch (SQLException e) { System.out.println("error al insertar registro en la tabla clientes general " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return inserto = false; } return inserto; }
public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } }
900,265
0
public void testGetResource_FileOutsideOfClasspath() throws Exception { File temp = File.createTempFile("dozerfiletest", ".txt"); temp.deleteOnExit(); String resourceName = "file:" + temp.getAbsolutePath(); URL url = loader.getResource(resourceName); assertNotNull("URL should not be null", url); InputStream is = url.openStream(); assertNotNull("input stream should not be null", is); }
public static synchronized String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new BASE64Encoder().encode(raw); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage()); } }
900,266
0
public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException { ZipFile zip = new ZipFile(mapPackFile); try { Enumeration<? extends ZipEntry> entries = zip.entries(); MessageDigest md5Total = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5"); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; String name = entry.getName(); if (name.toUpperCase().startsWith("META-INF")) continue; md5.reset(); InputStream in = zip.getInputStream(entry); byte[] data = Utilities.getInputBytes(in); in.close(); byte[] digest = md5.digest(data); log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\""); md5Total.update(digest); md5Total.update(name.getBytes()); } String md5sum = Hex.encodeHexString(md5Total.digest()); log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum); return md5sum; } finally { zip.close(); } }
public void testGetWithKeepAlive() throws Exception { HttpGet request = new HttpGet(baseUri + "/test"); HttpResponse response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); }
900,267
1
public Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; }
private static String makeTempTraceFile(String base) throws IOException { File temp = File.createTempFile(base, ".trace"); temp.deleteOnExit(); FileChannel dstChannel = new FileOutputStream(temp).getChannel(); FileChannel srcChannel = new FileInputStream(base + ".key").getChannel(); long size = dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = new FileInputStream(base + ".data").getChannel(); dstChannel.transferFrom(srcChannel, size, srcChannel.size()); srcChannel.close(); dstChannel.close(); return temp.getPath(); }
900,268
1
@Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); }
public static void copyFile(File source, File dest) throws Exception { FileInputStream fis = new FileInputStream(source); try { FileOutputStream fos = new FileOutputStream(dest); try { int read = fis.read(); while (read != -1) { fos.write(read); read = fis.read(); } } finally { fos.close(); } } finally { fis.close(); } }
900,269
1
private void copyFromZip(File zipFile) throws GLMRessourceManagerException { if (zipFile == null) throw new GLMRessourceZIPException(1); if (!zipFile.exists()) throw new GLMRessourceZIPException(2); int len = 0; byte[] buffer = ContentManager.getDefaultBuffer(); try { ZipInputStream zip_in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); ZipEntry zipEntry; File rootDir = null; while ((zipEntry = zip_in.getNextEntry()) != null) { File destFile = new File(tempDirectory, zipEntry.getName()); if (rootDir == null) rootDir = destFile.getParentFile(); if (!zipEntry.isDirectory() && destFile.getParentFile().equals(rootDir)) { if (!zipEntry.getName().equals(ContentManager.IMS_MANIFEST_FILENAME)) { FileOutputStream file_out = new FileOutputStream(new File(tempDirectory, zipEntry.getName())); while ((len = zip_in.read(buffer)) > 0) file_out.write(buffer, 0, len); file_out.flush(); file_out.close(); } } } zip_in.close(); } catch (Exception e) { throw new GLMRessourceZIPException(3); } }
public boolean clonarFichero(String rutaFicheroOrigen, String rutaFicheroDestino) { System.out.println(""); System.out.println("*********** DENTRO DE 'clonarFichero' ***********"); boolean estado = false; try { FileInputStream entrada = new FileInputStream(rutaFicheroOrigen); FileOutputStream salida = new FileOutputStream(rutaFicheroDestino); FileChannel canalOrigen = entrada.getChannel(); FileChannel canalDestino = salida.getChannel(); canalOrigen.transferTo(0, canalOrigen.size(), canalDestino); entrada.close(); salida.close(); estado = true; } catch (IOException e) { System.out.println("No se encontro el archivo"); e.printStackTrace(); estado = false; } return estado; }
900,270
0
public void fillTableValues() { java.util.ArrayList cpool = newgen.presentation.NewGenMain.getAppletInstance().getCataloguingPool(); String xmlreq = AdministrationXMLGenerator.getInstance().getPoolChronologicalSubDivision("4", cpool); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); java.util.List onelist = rootelement.getChildren(); for (int i = 0; i < onelist.size(); i++) { Element rec = (Element) onelist.get(i); Object[] r = new Object[7]; String[] chronolib = new String[2]; chronolib[0] = rec.getChild("ChronologicalSubDivisionId").getText(); chronolib[1] = rec.getChild("LibraryId").getText(); this.chronoid_libid.add(chronolib); r[0] = rec.getChild("ChronologicalSubDivision").getText(); this.dtmSearch.addRow(r); } } catch (Exception e) { System.out.println(e); } }
@Test public void test01_ok_failed_500() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(chartURL); HttpResponse response = client.execute(post); assertEquals("failed code for ", 500, response.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } }
900,271
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(); } }
private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } }
900,272
0
public String getImageURL(String text) { String imgURL = ""; try { URL url = new URL("http://images.search.yahoo.com/search/images?p=" + URLEncoder.encode(text)); URLConnection connection = url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); String line; Pattern imgPattern = Pattern.compile("isrc=\"([^\"]*)\""); while ((line = in.readLine()) != null) { Matcher match = imgPattern.matcher(line); if (match.find()) { imgURL = match.group(1); break; } } in.close(); } catch (Exception e) { } return imgURL; }
public static void fileCopy(String src, String dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); int read = -1; byte[] buf = new byte[8192]; while ((read = fis.read(buf)) != -1) { fos.write(buf, 0, read); } fos.flush(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
900,273
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; }
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(); } }
900,274
0
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!"); }
public GridDirectoryList(URL url) throws McIDASException { try { urlc = (AddeURLConnection) url.openConnection(); inputStream = new DataInputStream(new BufferedInputStream(urlc.getInputStream())); } catch (IOException e) { throw new McIDASException("Error opening URL for grids:" + e); } readDirectory(); }
900,275
1
public static void copyFile(File source, File target) { try { target.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }
public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
900,276
1
public void add(AddInterceptorChain chain, Entry entry, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + this.dbInsertName); String uid = ((RDN) (new DN(entry.getEntry().getDN())).getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.insertSQL); for (int i = 0; i < this.fields.size(); i++) { String field = this.fields.get(i); if (field.equals(this.rdnField)) { ps.setString(i + 1, uid); } else { ps.setString(i + 1, entry.getEntry().getAttribute(db2ldap.get(field)).getStringValue()); } } ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
public void add(AddInterceptorChain chain, Entry entry, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); PreparedStatement ps = con.prepareStatement("INSERT INTO USERS (id,firstname,lastname,username) VALUES (?,?,?,?)"); ps.setInt(1, 5); ps.setString(2, entry.getEntry().getAttribute(db2ldap.get("firstname")).getStringValue()); ps.setString(3, entry.getEntry().getAttribute(db2ldap.get("lastname")).getStringValue()); ps.setString(4, entry.getEntry().getAttribute(db2ldap.get("username")).getStringValue()); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); PreparedStatement inst = con.prepareStatement("INSERT INTO LOCATIONMAP (person,location) VALUES (?,?)"); LDAPAttribute l = entry.getEntry().getAttribute(db2ldap.get("name")); if (l == null) { con.rollback(); throw new LDAPException("Location is required", LDAPException.OBJECT_CLASS_VIOLATION, "Location is required"); } String[] vals = l.getStringValueArray(); for (int i = 0; i < vals.length; i++) { ps.setString(1, vals[i]); ResultSet rs = ps.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } inst.setInt(1, 5); inst.setInt(2, rs.getInt("id")); inst.executeUpdate(); } ps.close(); inst.close(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not add entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not add entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
900,277
0
public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
public static String MD5Encode(String password) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } return buf.toString(); } catch (NoSuchAlgorithmException e) { return password; } }
900,278
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; }
@SuppressWarnings("deprecation") public static final ReturnCode runCommand(IOBundle io, String[] args) { if ((args.length < 3) || (args.length > 4)) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 3) && (!args[1].equals("show"))) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 4) && (!(args[2].equals("training") || args[2].equals("log") || args[2].equals("configuration")))) return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Access denied to directory: " + args[2]); if (args[1].equals("open")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); io.println(fileName); io.println(file.length() + " bytes"); while (dis.available() != 0) { io.println(dis.readLine()); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_NOT_FOUND, "File " + fileName + " doesn't exist"); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error reading File " + fileName); } } else if (args[1].equals("save")) { final String fileName = args[2] + "/" + args[3]; String line; try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); line = io.readLine(); int count = Integer.parseInt(line.trim()); while (count > 0) { out.write(io.read()); count = count - 1; } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error writing File " + fileName); } } else if (args[1].equals("delete")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); if (!file.exists()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such file or directory: " + fileName); if (!file.canWrite()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "File is write-protected: " + fileName); if (file.isDirectory()) { String[] files = file.list(); if (files.length > 0) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Directory is not empty: " + fileName); } if (!file.delete()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Deletion failed: " + fileName); } else if (args[1].equals("show")) { File directory = new File(args[2]); String[] files; if ((!directory.isDirectory()) || (!directory.exists())) { return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such directory: " + directory); } int count = 0; files = directory.list(); io.println("Files in directory \"" + directory + "\":"); for (int i = 0; i < files.length; i++) { directory = new File(files[i]); if (!directory.isDirectory()) { count++; io.println(" " + files[i]); } } io.println("Total " + count + " files"); } else return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Unrecognized command"); return ReturnCode.makeReturnCode(ReturnCode.RET_OK); }
900,279
1
public void testRoundTrip_1(String resource) throws Exception { long start1 = System.currentTimeMillis(); File originalFile = File.createTempFile("RoundTripTest", "testRoundTrip_1"); FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(getClass().getResourceAsStream(resource), fos); fos.close(); long start2 = System.currentTimeMillis(); IsoFile isoFile = new IsoFile(new FileInputStream(originalFile).getChannel()); long start3 = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(baos); long start4 = System.currentTimeMillis(); Walk.through(isoFile); long start5 = System.currentTimeMillis(); isoFile.getBox(wbc); wbc.close(); long start6 = System.currentTimeMillis(); System.err.println("Preparing tmp copy took: " + (start2 - start1) + "ms"); System.err.println("Parsing took : " + (start3 - start2) + "ms"); System.err.println("Writing took : " + (start6 - start3) + "ms"); System.err.println("Walking took : " + (start5 - start4) + "ms"); byte[] a = IOUtils.toByteArray(getClass().getResourceAsStream(resource)); byte[] b = baos.toByteArray(); Assert.assertArrayEquals(a, b); }
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
900,280
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(); } }
public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } }
900,281
1
private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); }
public static void copyFile(File in, File outDir) throws IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); File out = new File(outDir, in.getName()); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { if (sourceChannel != null) { sourceChannel.close(); } } finally { if (destinationChannel != null) { destinationChannel.close(); } } } }
900,282
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; }
@Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } }
900,283
0
public static String sha1(String clearText, String seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update((seed + clearText).getBytes()); return convertToHex(md.digest()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
public static void downloadFromUrl(URL url, String localFilename, String userAgent) throws IOException { InputStream is = null; FileOutputStream fos = null; System.setProperty("java.net.useSystemProxies", "true"); try { URLConnection urlConn = url.openConnection(); if (userAgent != null) { urlConn.setRequestProperty("User-Agent", userAgent); } is = urlConn.getInputStream(); fos = new FileOutputStream(localFilename); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } }
900,284
1
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); } } }
protected void checkWeavingJar() throws IOException { OutputStream out = null; try { final File weaving = new File(getWeavingPath()); if (!weaving.exists()) { new File(getWeavingFolder()).mkdir(); weaving.createNewFile(); final Path src = new Path("weaving/openfrwk-weaving.jar"); final InputStream in = FileLocator.openStream(getBundle(), src, false); out = new FileOutputStream(getWeavingPath(), true); IOUtils.copy(in, out); Logger.log(Logger.INFO, "Put weaving jar at location " + weaving); } else { Logger.getLog().info("File openfrwk-weaving.jar already exists at " + weaving); } } catch (final SecurityException e) { Logger.log(Logger.ERROR, "[SECURITY EXCEPTION] Not enough privilegies to create " + "folder and copy NexOpen weaving jar at location " + getWeavingFolder()); Logger.logException(e); } finally { if (out != null) { out.flush(); out.close(); } } }
900,285
1
protected void setUp() throws Exception { testOutputDirectory = new File(getClass().getResource("/").getPath()); zipFile = new File(this.testOutputDirectory, "/plugin.zip"); zipOutputDirectory = new File(this.testOutputDirectory, "zip"); zipOutputDirectory.mkdir(); logger.fine("zip dir created"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry("css/")); zos.putNextEntry(new ZipEntry("css/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("js/")); zos.putNextEntry(new ZipEntry("js/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/mylib.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/mylib.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); }
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { String context = request.getContextPath(); String resource = request.getRequestURI().replace(context, ""); resource = resource.replaceAll("^/\\w*/", ""); if ((StringUtils.isEmpty(resource)) || (resource.endsWith("/"))) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } URL url = ClassLoaderUtils.getResource(resource); if (url == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if ((this.deny != null) && (this.deny.length > 0)) { for (String s : this.deny) { s = s.trim(); if (s.indexOf('*') != -1) { s = s.replaceAll("\\*", ".*"); } if (Pattern.matches(s, resource)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } } InputStream input = url.openStream(); OutputStream output = response.getOutputStream(); URLConnection connection = url.openConnection(); String contentEncoding = connection.getContentEncoding(); int contentLength = connection.getContentLength(); String contentType = connection.getContentType(); if (contentEncoding != null) { response.setCharacterEncoding(contentEncoding); } response.setContentLength(contentLength); response.setContentType(contentType); IOUtils.copy(input, output, true); }
900,286
0
public static int[] sortDescending(float input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] < input[j + 1]) { float mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
public static Coordinate getCoordenadas(String RCoURL) { Coordinate coord = new Coordinate(); String pURL; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniX = "<xcen>"; String iniY = "<ycen>"; String finX = "</xcen>"; String finY = "</ycen>"; String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; boolean error = false; int ini, fin; if (RCoURL.contains("/") || RCoURL.contains("\\") || RCoURL.contains(".")) pURL = RCoURL; else { if (RCoURL.length() > 14) pURL = baseURL[1].replace("<RC>", RCoURL.substring(0, 14)); else pURL = baseURL[1].replace("<RC>", RCoURL); } try { URL url = new URL(pURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); coord.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); coord.setDescription(coord.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniX)) { ini = str.indexOf(iniX) + iniX.length(); fin = str.indexOf(finX); coord.setLongitude(Double.parseDouble(str.substring(ini, fin))); } if (str.contains(iniY)) { ini = str.indexOf(iniY) + iniY.length(); fin = str.indexOf(finY); coord.setLatitude(Double.parseDouble(str.substring(ini, fin))); } } } in.close(); } catch (Exception e) { System.err.println(e); } return coord; }
900,287
0
public String post(Map<String, String> headersMap, String monitoringRequest) { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.useragent", "sla@soi OCCI Client v0.2"); HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + resource); List<Header> headersList = this.convert2Headers(headersMap); for (Iterator<Header> iterator = headersList.iterator(); iterator.hasNext(); ) { httpPost.addHeader(iterator.next()); } if (monitoringRequest == null) { logger.info("Monitoring Request has not been specified - "); monitoringRequest = Terms.MONITORING_NOT_CONFIGURED; logger.info("Monitoring Request has not been specified - " + monitoringRequest); } else { logger.info("Monitoring Request is - " + monitoringRequest); } logger.info(httpPost.getRequestLine()); logger.info(httpPost.getAllHeaders()); Header[] headersArray = httpPost.getAllHeaders(); String[] fields = { Response.Location }; HashMap<String, String> occiHeaders = new HashMap<String, String>(); for (int H = 0; H < headersArray.length; H++) { Header header = headersArray[H]; logger.info("header - request -" + header.toString()); logger.info(" headerName - " + header.getName()); logger.info(" headerValue - " + header.getValue()); } String statusLine = null; try { HttpResponse httpResponse = httpClient.execute(httpPost); statusLine = httpResponse.getStatusLine().toString(); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.info("----------------------------------------"); logger.info("StatusLine - (full) - " + httpResponse.getStatusLine()); logger.info(" StatusCode - " + statusCode); logger.info(" Reason - " + httpResponse.getStatusLine().getReasonPhrase()); logger.info(" Protocol - " + httpResponse.getStatusLine().getProtocolVersion().toString()); logger.info("----------------------------------------"); if (StatusCode.validate(statusCode)) { logger.info("Response Validated"); } else { logger.error("Response NOT Validated"); } Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; logger.info("header - response - " + header.toString()); logger.info(" headerName - " + header.getName()); logger.info(" headerValue - " + header.getValue()); for (int h = 0; h < fields.length; h++) { logger.info(" Looking for - " + fields[h]); if (fields[h].equals(header.getName().toString())) { logger.info(" Found an OCCI Header - " + header.getName()); occiHeaders.put(header.getName(), header.getValue()); } } } } catch (org.apache.http.conn.HttpHostConnectException e) { e.printStackTrace(); logger.error(e); return null; } catch (ClientProtocolException e) { e.printStackTrace(); logger.error(e); return null; } catch (IOException e) { e.printStackTrace(); logger.error(e); return null; } finally { httpClient.getConnectionManager().shutdown(); } logger.info("occiHeaders - " + occiHeaders); if (occiHeaders.containsKey(Response.Location)) { logger.info("Valid Provision"); return occiHeaders.get(Response.Location).toString().replaceAll(Response.jobs, ""); } logger.info("NOT a Valid Provision" + statusLine); return null; }
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); } }
900,288
1
public String Hash(String plain) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes(), 0, plain.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (Exception ex) { Log.serverlogger.warn("No such Hash algorithm", ex); return ""; } }
public static boolean verify(final String password, final String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } final byte[] data = Base64.decode(base64.toCharArray()); final byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
900,289
1
public void writeToFile(File file, File source) throws IOException { BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file)); BufferedInputStream bin = new BufferedInputStream(new FileInputStream(source)); bin.skip(header.getHeaderEndingOffset()); for (long i = 0; i < this.streamLength; i++) { bout.write(bin.read()); } bin.close(); bout.close(); }
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; }
900,290
0
@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; }
public static final String generate(String value) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(value.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } value = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return value; }
900,291
0
private String hash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); }
private String doSearch(String query) { StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("http://boss.yahooapis.com/ysearch/web/v1/").append(query).append("?appid=wGsFV_DV34EwXnC.2Bt_Ql8Kcir_HmrxMzWUF2fv64CA8ha7e4zgudqXFA8K_J4-&format=xml&filter=-porn"); try { URL url = new URL(queryBuilder.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); return safeParseXml(buffer.toString()); } catch (MalformedURLException e) { log.error("The used url is not right : " + queryBuilder.toString(), e); return "The used url is not right."; } catch (IOException e) { log.error("Problem obtaining search results, connection maybe?", e); return "Problem obtaining search results, connection maybe?"; } }
900,292
1
public static List importSymbols(List symbols) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbols); IDQuoteFilter filter = new YahooIDQuoteFilter(); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; do { line = bufferedInput.readLine(); if (line != null) { try { IDQuote quote = filter.toIDQuote(line); quote.verify(); quotes.add(quote); } catch (QuoteFormatException e) { } } } while (line != null); bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
private void init(URL url) { frame = new JInternalFrame(name); frame.addInternalFrameListener(this); listModel.add(listModel.size(), this); area = new JTextArea(); area.setMargin(new Insets(5, 5, 5, 5)); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String in; while ((in = reader.readLine()) != null) { area.append(in); area.append("\n"); } reader.close(); } catch (Exception e) { e.printStackTrace(); return; } th = area.getTransferHandler(); area.setFont(new Font("monospaced", Font.PLAIN, 12)); area.setCaretPosition(0); area.setDragEnabled(true); area.setDropMode(DropMode.INSERT); frame.getContentPane().add(new JScrollPane(area)); dp.add(frame); frame.show(); if (DEMO) { frame.setSize(300, 200); } else { frame.setSize(400, 300); } frame.setResizable(true); frame.setClosable(true); frame.setIconifiable(true); frame.setMaximizable(true); frame.setLocation(left, top); incr(); SwingUtilities.invokeLater(new Runnable() { public void run() { select(); } }); nullItem.addActionListener(this); setNullTH(); }
900,293
0
private void copyFile(File sourceFile, File destFile) throws IOException { if (log.isDebugEnabled()) { log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]"); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
@Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } }
900,294
1
public static void TestDBStore() throws PDException, Exception { StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB"); System.out.println("Driver[" + StDB.getDriver() + "] Tabla [" + StDB.getTable() + "]"); StDB.Connect(); FileInputStream in = new FileInputStream("/tmp/readme.htm"); StDB.Insert("12345678-1", "1.0", in); int TAMBUFF = 1024 * 64; byte Buffer[] = new byte[TAMBUFF]; InputStream Bytes; Bytes = StDB.Retrieve("12345678-1", "1.0"); FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm"); int readed = Bytes.read(Buffer); while (readed != -1) { fo.write(Buffer, 0, readed); readed = Bytes.read(Buffer); } Bytes.close(); fo.close(); StDB.Delete("12345678-1", "1.0"); StDB.Disconnect(); }
public static void main(String[] argz) { int X, Y, Z; X = 256; Y = 256; Z = 256; try { String work_folder = "C:\\Documents and Settings\\Entheogen\\My Documents\\school\\jung\\vol_data\\CT_HEAD3"; FileOutputStream out_stream = new FileOutputStream(new File(work_folder + "\\converted.dat")); FileChannel out = out_stream.getChannel(); String f_name = "head256.raw"; File file = new File(work_folder + "\\" + f_name); FileChannel in = new FileInputStream(file).getChannel(); ByteBuffer buffa = BufferUtil.newByteBuffer((int) file.length()); in.read(buffa); in.close(); int N = 256; FloatBuffer output_data = BufferUtil.newFloatBuffer(N * N * N); float min = Float.MAX_VALUE; for (int i = 0, j = 0; i < buffa.capacity(); i++, j++) { byte c = buffa.get(i); min = Math.min(min, (float) (c)); output_data.put((float) (c)); } for (int i = 0; i < Y - X; ++i) { for (int j = 0; j < Y; ++j) { for (int k = 0; k < Z; ++k) { output_data.put(min); } } } output_data.rewind(); System.out.println("size of output_data = " + Integer.toString(output_data.capacity())); out.write(BufferUtil.copyFloatBufferAsByteBuffer(output_data)); ByteBuffer buffa2 = BufferUtil.newByteBuffer(2); buffa2.put((byte) '.'); out.close(); } catch (Exception exc) { exc.printStackTrace(); } }
900,295
0
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); }
private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
900,296
1
public static final boolean checkForUpdate(final String currentVersion, final String updateURL, boolean noLock) throws Exception { try { final String parentFDTConfDirName = System.getProperty("user.home") + File.separator + ".fdt"; final String fdtUpdateConfFileName = "update.properties"; final File confFile = createOrGetRWFile(parentFDTConfDirName, fdtUpdateConfFileName); if (confFile != null) { long lastCheck = 0; Properties updateProperties = new Properties(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(confFile); updateProperties.load(fis); final String lastCheckProp = (String) updateProperties.get("LastCheck"); lastCheck = 0; if (lastCheckProp != null) { try { lastCheck = Long.parseLong(lastCheckProp); } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Got exception parsing LastCheck param", t); } lastCheck = 0; } } } catch (Throwable t) { logger.log(Level.WARNING, "Cannot load update properties file: " + confFile, t); } finally { closeIgnoringExceptions(fos); closeIgnoringExceptions(fis); } final long now = System.currentTimeMillis(); boolean bHaveUpdates = false; checkAndSetInstanceID(updateProperties); if (lastCheck + FDT.UPDATE_PERIOD < now) { lastCheck = now; try { logger.log("\n\nChecking for remote updates ... This may be disabled using -noupdates flag."); bHaveUpdates = updateFDT(currentVersion, updateURL, false, noLock); if (bHaveUpdates) { logger.log("FDT may be updated using: java -jar fdt.jar -update"); } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "No updates available"); } } } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.WARNING, "Got exception", t); } } updateProperties.put("LastCheck", "" + now); try { fos = new FileOutputStream(confFile); updateProperties.store(fos, null); } catch (Throwable t1) { logger.log(Level.WARNING, "Cannot store update properties file", t1); } finally { closeIgnoringExceptions(fos); } return bHaveUpdates; } } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, " [ checkForUpdate ] Cannot read or write the update conf file: " + parentFDTConfDirName + File.separator + fdtUpdateConfFileName); } return false; } } catch (Throwable t) { logger.log(Level.WARNING, "Got exception checking for updates", t); } return false; }
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
900,297
0
private void sendMessages() { Configuration conf = Configuration.getInstance(); for (int i = 0; i < errors.size(); i++) { String msg = null; synchronized (this) { msg = errors.get(i); if (DEBUG) System.out.println(msg); errors.remove(i); } if (!conf.getCustomerFeedback()) continue; if (conf.getApproveCustomerFeedback()) { ConfirmCustomerFeedback dialog = new ConfirmCustomerFeedback(JOptionPane.getFrameForComponent(SqlTablet.getInstance()), msg); if (dialog.getResult() == ConfirmCustomerFeedback.Result.NO) continue; } try { URL url = new URL("http://www.sqltablet.com/beta/bug.php"); URLConnection urlc = url.openConnection(); urlc.setDoOutput(true); urlc.setDoOutput(true); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(urlc.getOutputStream()); String lines[] = msg.split("\n"); for (int l = 0; l < lines.length; l++) { String line = (l > 0 ? "&line" : "line") + l + "="; line += URLEncoder.encode(lines[l], "UTF-8"); out.write(line.getBytes()); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line; while ((line = in.readLine()) != null) { if (DEBUG) System.out.println("RemoteLogger : " + line + "\n"); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
900,298
1
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); 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) { ; } } }
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; }
900,299