label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public DownloadThread call() throws UpdateModException { try { Thread.currentThread().setName("Download - " + modName); if (url != null) { URL urls = new URL(this.url); URLConnection connection = urls.openConnection(); connection.setConnectTimeout(7500); InputStream is = urls.openStream(); String filename = null; if (path == null || path.isEmpty()) { String pattern = "[^a-z,A-Z,0-9, ,.]"; filename = this.url.substring(this.url.lastIndexOf("/") + 1).replace("%20", " "); filename = filename.replaceAll(pattern, ""); } else { filename = path; } FileOutputStream fos = null; file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename); fos = new FileOutputStream(file, false); FileUtils.copyInputStream(is, fos); is.close(); fos.flush(); fos.close(); } } catch (MalformedURLException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (ConnectException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (NullPointerException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (InvalidParameterException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (FileNotFoundException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (IOException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } return this; } Code Sample 2: public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
00
Code Sample 1: public RemotePolicyMigrator createRemotePolicyMigrator() { return new RemotePolicyMigrator() { public String migratePolicy(InputStream stream, String url) throws ResourceMigrationException, IOException { ByteArrayOutputCreator oc = new ByteArrayOutputCreator(); IOUtils.copyAndClose(stream, oc.getOutputStream()); return oc.getOutputStream().toString(); } }; } Code Sample 2: public void init() { updateLoc = "none"; mt = new MediaTracker(this); thisThread = new Thread(this); i = 0; thisThread.start(); try { base = getDocumentBase(); username = getParameter("username"); } catch (Exception e) { } String userpng = "images/" + username + ".png"; String userdat = "data/" + username + "_l.cod"; URL url = null; try { url = new URL(base, userdat); } catch (MalformedURLException e1) { } InputStream in = null; try { in = url.openStream(); } catch (IOException e1) { } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); } catch (Exception r) { } try { String line = reader.readLine(); StringTokenizer tokenizer = new StringTokenizer(line, " "); int dim = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); this.topol = tokenizer.nextToken().trim().toLowerCase(); xunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); yunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); @SuppressWarnings("unused") String neigh = tokenizer.nextToken().trim().toLowerCase(); String label = null; labels = new String[xunit][yunit]; for (int e = 0; e < yunit; e++) { for (int r = 0; r < xunit; r++) { line = reader.readLine(); StringTokenizer tokenizer2 = new StringTokenizer(line, " "); for (int w = 0; w < dim; w++) { if (tokenizer2.countTokens() > 0) tokenizer2.nextToken(); } while (tokenizer2.countTokens() > 0) { label = tokenizer2.nextToken() + " "; } if (label == null) { labels[r][e] = "none"; } else { labels[r][e] = label; } label = null; } } reader.close(); if (topol.equals("hexa")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { if (q % 2 == 0) { double nenner = (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } if (q % 2 != 0) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } if (topol.equals("rect")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round((nenner / divisor1)); yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } } catch (IOException o) { } umat = getImage(base, userpng); mt.addImage(umat, 1); try { mt.waitForAll(); } catch (InterruptedException e) { } addMouseListener(new CircleInfo()); }
00
Code Sample 1: @Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static void main(String[] args) { if (args.length != 2) { printUsage(); } String url = args[0]; String path = args[1]; BufferedReader pbsFileReader = null; try { pbsFileReader = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException ex) { System.err.println("Pbs file " + path + " not found"); System.exit(1); } String line = ""; HttpURLConnection conn = null; BufferedWriter out = null; BufferedReader in = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); while (true) { line = pbsFileReader.readLine(); if (line == null) { break; } out.write(line); out.newLine(); System.err.println(line); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); line = ""; while (true) { line = in.readLine(); if (line == null) { break; } System.out.println(line); } out.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } Code Sample 2: public static boolean loadTestProperties(Properties props, Class<?> callingClazz, Class<?> hierarchyRootClazz, String resourceBaseName) { if (!hierarchyRootClazz.isAssignableFrom(callingClazz)) { throw new IllegalArgumentException("Class " + callingClazz + " is not derived from " + hierarchyRootClazz); } if (null == resourceBaseName) { throw new NullPointerException("resourceBaseName is null"); } String fqcn = callingClazz.getName(); String uqcn = fqcn.substring(fqcn.lastIndexOf('.') + 1); String callingClassResource = uqcn + ".properties"; String globalCallingClassResource = "/" + callingClassResource; String baseClassResource = resourceBaseName + "-" + uqcn + ".properties"; String globalBaseClassResource = "/" + baseClassResource; String pkgResource = resourceBaseName + ".properties"; String globalResource = "/" + pkgResource; boolean loaded = false; final String[] resources = { baseClassResource, globalBaseClassResource, callingClassResource, globalCallingClassResource, pkgResource, globalResource }; List<URL> urls = new ArrayList<URL>(); Class<?> clazz = callingClazz; do { for (String res : resources) { URL url = clazz.getResource(res); if (null != url && !urls.contains(url)) { urls.add(url); } } if (hierarchyRootClazz.equals(clazz)) { clazz = null; } else { clazz = clazz.getSuperclass(); } } while (null != clazz); ListIterator<URL> it = urls.listIterator(urls.size()); while (it.hasPrevious()) { URL url = it.previous(); InputStream in = null; try { LOG.info("Loading test properties from resource: " + url); in = url.openStream(); props.load(in); loaded = true; } catch (IOException ex) { LOG.warn("Failed to load properties from resource: " + url, ex); } IOUtil.closeSilently(in); } return loaded; }
00
Code Sample 1: private void download(String address, String localFileName, String host, int porta) { InputStream in = null; URLConnection conn = null; OutputStream out = null; System.out.println("Update.download() BAIXANDO " + address); try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); if (host != "" && host != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, porta)); conn = url.openConnection(proxy); } else { conn = url.openConnection(); } in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } } Code Sample 2: public byte[] loadClassFirst(final String className) { if (className.startsWith("com.sun.sgs.impl.service.transaction.TransactionCoordinatorImpl")) { String resource = null; if (className.equals("com.sun.sgs.impl.service.transaction.TransactionCoordinatorImpl")) { resource = "com/sun/sgs/impl/service/transaction/TransactionCoordinatorImpl.class.bin"; } if (resource != null) { final URL url = Thread.currentThread().getContextClassLoader().getResource(resource); if (url != null) { try { return StreamUtil.read(url.openStream()); } catch (final IOException e) { } } throw new IllegalStateException("Unable to load binary class"); } } return null; }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public static void copyFile(final FileInputStream in, final File out) throws IOException { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 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); } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { guiBuilder.showError("Copy Error", "IOException during copy", ioe.getMessage()); return false; } }
11
Code Sample 1: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.substring(8, 24).toString().toUpperCase(); } Code Sample 2: private String calculateMD5(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(input.getBytes()); byte[] md5 = digest.digest(); String tmp = ""; String res = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } return res; }
11
Code Sample 1: public static void copyFile(File from, File to) throws IOException { ensureFile(to); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
00
Code Sample 1: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } } Code Sample 2: public static int sendButton(String url, String id, String command) throws ClientProtocolException, IOException { String connectString = url + "/rest/button/" + id + "/" + command; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(connectString); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); return code; }
00
Code Sample 1: private void createTree(DefaultMutableTreeNode top) throws MalformedURLException, ParserConfigurationException, SAXException, IOException { InputStream stream; URL url = new URL(SHIPS_URL + view.getBaseurl()); try { stream = url.openStream(); } catch (Exception e) { stream = getClass().getResourceAsStream("ships.xml"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(stream); NodeList races = doc.getElementsByTagName("race"); for (int i = 0; i < races.getLength(); i++) { Element race = (Element) races.item(i); top.add(buildRaceTree(race)); } top.setUserObject("Ships"); view.getShipTree().repaint(); view.getShipTree().expandRow(0); } Code Sample 2: public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { Logger.error(FileUtil.class, ioe.getMessage(), ioe); } } Code Sample 2: public void constructFundamentalView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { FundView = new BufferedWriter(new FileWriter("InfoFiles/FundamentalView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; FundView.write(className); FundView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; FundView.write("StartOfMethod"); FundView.newLine(); FundView.write(methodName); FundView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(readArray[i + j]); FundView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(writeArray[i + j]); FundView.newLine(); } } } } } FundView.write("EndOfMethod"); FundView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { FundView.write("EndOfClass"); FundView.newLine(); classWritten = false; } } PC.close(); FundView.close(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
11
Code Sample 1: public void create(Session session) { Connection conn = session.getConnection(this); Statement stat = null; StringBuilder out = new StringBuilder(256); Appendable sql = out; List<MetaTable> tables = new ArrayList<MetaTable>(); List<MetaColumn> newColumns = new ArrayList<MetaColumn>(); List<MetaColumn> foreignColumns = new ArrayList<MetaColumn>(); List<MetaIndex> indexes = new ArrayList<MetaIndex>(); boolean createSequenceTable = false; int tableTotalCount = getTableTotalCount(); try { stat = conn.createStatement(); if (isSequenceTableRequired()) { PreparedStatement ps = null; ResultSet rs = null; Throwable exception = null; String logMsg = ""; try { sql = getDialect().printSequenceCurrentValue(findFirstSequencer(), out); ps = conn.prepareStatement(sql.toString()); ps.setString(1, "-"); rs = ps.executeQuery(); } catch (Throwable e) { exception = e; } if (exception != null) { switch(MetaParams.ORM2DLL_POLICY.of(ormHandler.getParameters())) { case VALIDATE: throw new IllegalStateException(logMsg, exception); case CREATE_DDL: case CREATE_OR_UPDATE_DDL: createSequenceTable = true; } } if (LOGGER.isLoggable(Level.INFO)) { logMsg = "Table '" + SqlDialect.COMMON_SEQ_TABLE_NAME + "' {0} available on the database '{1}'."; logMsg = MessageFormat.format(logMsg, exception != null ? "is not" : "is", getId()); LOGGER.log(Level.INFO, logMsg); } try { if (exception != null) { conn.rollback(); } } finally { close(null, ps, rs, false); } } boolean ddlOnly = false; switch(MetaParams.ORM2DLL_POLICY.of(ormHandler.getParameters())) { case CREATE_DDL: ddlOnly = true; case CREATE_OR_UPDATE_DDL: case VALIDATE: boolean change = isModelChanged(conn, tables, newColumns, indexes); if (change && ddlOnly) { if (tables.size() < tableTotalCount) { return; } } break; case DO_NOTHING: default: return; } switch(MetaParams.CHECK_KEYWORDS.of(getParams())) { case WARNING: case EXCEPTION: Set<String> keywords = getDialect().getKeywordSet(conn); for (MetaTable table : tables) { if (table.isTable()) { checkKeyWord(MetaTable.NAME.of(table), table, keywords); for (MetaColumn column : MetaTable.COLUMNS.of(table)) { checkKeyWord(MetaColumn.NAME.of(column), table, keywords); } } } for (MetaColumn column : newColumns) { checkKeyWord(MetaColumn.NAME.of(column), column.getTable(), keywords); } for (MetaIndex index : indexes) { checkKeyWord(MetaIndex.NAME.of(index), MetaIndex.TABLE.of(index), keywords); } } if (tableTotalCount == tables.size()) for (String schema : getSchemas(tables)) { out.setLength(0); sql = getDialect().printCreateSchema(schema, out); if (isUsable(sql)) { try { stat.executeUpdate(sql.toString()); } catch (SQLException e) { LOGGER.log(Level.INFO, "{0}: {1}; {2}", new Object[] { e.getClass().getName(), sql.toString(), e.getMessage() }); conn.rollback(); } } } int tableCount = 0; for (MetaTable table : tables) { if (table.isTable()) { tableCount++; out.setLength(0); sql = getDialect().printTable(table, out); executeUpdate(sql, stat); foreignColumns.addAll(table.getForeignColumns()); } } for (MetaColumn column : newColumns) { out.setLength(0); sql = getDialect().printAlterTable(column, out); executeUpdate(sql, stat); if (column.isForeignKey()) { foreignColumns.add(column); } } for (MetaIndex index : indexes) { out.setLength(0); sql = getDialect().printIndex(index, out); executeUpdate(sql, stat); } for (MetaColumn column : foreignColumns) { if (column.isForeignKey()) { out.setLength(0); MetaTable table = MetaColumn.TABLE.of(column); sql = getDialect().printForeignKey(column, table, out); executeUpdate(sql, stat); } } if (createSequenceTable) { out.setLength(0); sql = getDialect().printSequenceTable(this, out); executeUpdate(sql, stat); } List<MetaTable> cTables = null; switch(MetaParams.COMMENT_POLICY.of(ormHandler.getParameters())) { case FOR_NEW_OBJECT: cTables = tables; break; case ALWAYS: case ON_ANY_CHANGE: cTables = TABLES.getList(this); break; case NEVER: cTables = Collections.emptyList(); break; default: throw new IllegalStateException("Unsupported parameter"); } if (!cTables.isEmpty()) { sql = out; createTableComments(cTables, stat, out); } conn.commit(); } catch (Throwable e) { try { conn.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Can't rollback DB" + getId(), ex); } throw new IllegalArgumentException(Session.SQL_ILLEGAL + sql, e); } } Code Sample 2: private void duplicateTable(Connection scon, Connection dcon, String table) { logger.debug("Duplicating table " + table); Statement creTab, stmt; ResultSet tuples, columns, keys; int c; String insert = ""; PreparedStatement insTup; try { columns = scon.getMetaData().getColumns(null, null, table, null); keys = scon.getMetaData().getPrimaryKeys(null, null, table); creTab = dcon.createStatement(); creTab.execute(getCreateTableCommand(columns, keys)); stmt = scon.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(50); tuples = stmt.executeQuery("SELECT * FROM " + table); c = tuples.getMetaData().getColumnCount(); insert = "INSERT INTO " + table + " VALUES("; for (int j = 1; j <= c; j++) insert += "?,"; insert = insert.substring(0, insert.length() - 1) + ")"; logger.debug("Insert pattern " + insert); insTup = dcon.prepareStatement(insert); while (tuples.next()) { for (int j = 1; j <= c; j++) insTup.setObject(j, tuples.getObject(j)); insTup.executeUpdate(); } dcon.commit(); } catch (Exception e) { logger.error("Unable to copy table " + table + ": " + e); try { dcon.rollback(); } catch (SQLException e1) { logger.fatal(e1); } } }
00
Code Sample 1: private void copy(URL url, IFile file, IProgressMonitor monitor) throws CoreException, IOException { InputStream input = null; try { input = url.openStream(); if (file.exists()) { file.setContents(input, IResource.FORCE, monitor); } else { file.create(input, IResource.FORCE, monitor); } } finally { if (input != null) { try { input.close(); } catch (IOException ignore) { } } } } Code Sample 2: public void testReleaseOnIOException() throws Exception { localServer.register("/dropdead", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { BasicHttpEntity entity = new BasicHttpEntity() { @Override public void writeTo(final OutputStream outstream) throws IOException { byte[] tmp = new byte[5]; outstream.write(tmp); outstream.flush(); DefaultHttpServerConnection conn = (DefaultHttpServerConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION); try { conn.sendResponseHeader(response); } catch (HttpException ignore) { } } }; entity.setChunked(true); response.setEntity(entity); } }); 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("/dropdead"); 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); try { EntityUtils.toByteArray(e); fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException expected) { } assertEquals(0, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static Set<Province> getProvincias(String pURL) { Set<Province> result = new HashSet<Province>(); String iniProv = "<prov>"; String finProv = "</prov>"; String iniNomProv = "<np>"; String finNomProv = "</np>"; String iniCodigo = "<cpine>"; String finCodigo = "</cpine>"; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Province provincia; while ((str = br.readLine()) != null) { if (str.contains(iniProv)) { provincia = new Province(); while ((str = br.readLine()) != null && !str.contains(finProv)) { if (str.contains(iniNomProv)) { ini = str.indexOf(iniNomProv) + iniNomProv.length(); fin = str.indexOf(finNomProv); provincia.setDescription(str.substring(ini, fin)); } if (str.contains(iniCodigo)) { ini = str.indexOf(iniCodigo) + iniCodigo.length(); fin = str.indexOf(finCodigo); provincia.setCodeProvince(Integer.parseInt(str.substring(ini, fin))); } } result.add(provincia); } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
11
Code Sample 1: public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { throw new RuntimeException("Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("NoSuchAlgorithmException : " + e.getMessage()); } return digest; } Code Sample 2: public String encodePassword(String password, byte[] salt) throws Exception { if (salt == null) { salt = new byte[12]; secureRandom.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(salt, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new String(Base64.encode(storedPassword)); }
00
Code Sample 1: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } } Code Sample 2: public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileOutputStream lfosTargetFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfosTargetFile = new FileOutputStream(mstrTargetDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrSourceDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrSourceDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.retrieveFile(mstrFilename, lfosTargetFile)) { throw new Exception("Unable to download [ " + mstrSourceDirectory + "/" + mstrFilename + " to " + mstrTargetDirectory + File.separator + mstrFilename + " ] from server [ " + mstrRemoteServer + " ]"); } lfosTargetFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfosTargetFile != null) { try { lfosTargetFile.close(); } catch (Exception e) { } } } }
00
Code Sample 1: @Override public String addUserIdentity(OpenIDItem identity, long userId) throws DatabaseException { if (identity == null) throw new NullPointerException("identity"); if (identity.getIdentity() == null || "".equals(identity.getIdentity())) throw new NullPointerException("identity.getIdentity()"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; PreparedStatement insSt = null, seqSt = null; try { int modified = 0; insSt = getConnection().prepareStatement(INSERT_IDENTITY_STATEMENT); insSt.setLong(1, userId); insSt.setString(2, identity.getIdentity()); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_IDENTITY_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + insSt + "\""); } else { getConnection().rollback(); LOGGER.debug("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + insSt + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } return retID; } Code Sample 2: private CathUtils() throws Exception { super(Ontology.CATH); InputStream is = null; BufferedReader reader = null; try { final String CATH_REGEXP = OntologyFactory.getOntology(Ontology.CATH).getRegularExpression(); final URL url = new URL("http://release.cathdb.info/v3.4.0/CathNames"); is = url.openStream(); reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset())); String line = null; while ((line = reader.readLine()) != null) { final String[] tokens = line.split("\\s+"); if (RegularExpressionUtils.getMatches(tokens[0], CATH_REGEXP).size() > 0) { idToName.put(tokens[0], line.substring(line.indexOf(':') + 1, line.length())); } } } finally { try { if (is != null) { is.close(); } } finally { if (reader != null) { reader.close(); } } } }
11
Code Sample 1: public static String generateNonce(boolean is32) { Random random = new Random(); String result = String.valueOf(random.nextInt(9876599) + 123400); if (is32) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(result.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; } Code Sample 2: protected byte[] getHashedID(String ID) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(ID.getBytes()); byte[] digest = md5.digest(); byte[] bytes = new byte[WLDB_ID_SIZE]; for (int i = 0; i < bytes.length; i++) { bytes[i] = digest[i]; } return bytes; } catch (NoSuchAlgorithmException exception) { System.err.println("Java VM is not compatible"); exit(); return null; } }
00
Code Sample 1: @Override public void save(String arxivId, InputStream inputStream, String encoding) { String filename = StringUtil.arxivid2filename(arxivId, "tex"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(String.format("%s/%s", LATEX_DOCUMENT_DIR, filename)), encoding); IOUtils.copy(inputStream, writer, encoding); writer.flush(); writer.close(); inputStream.close(); } catch (IOException e) { logger.error("Failed to save the Latex source with id='{}'", arxivId, e); throw new RuntimeException(e); } } Code Sample 2: public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
00
Code Sample 1: private String generateCode(String seed) { try { Security.addProvider(new FNVProvider()); MessageDigest digest = MessageDigest.getInstance("FNV-1a"); digest.update((seed + UUID.randomUUID().toString()).getBytes()); byte[] hash1 = digest.digest(); String sHash1 = "m" + (new String(LibraryBase64.encode(hash1))).replaceAll("=", "").replaceAll("-", "_"); return sHash1; } catch (Exception e) { e.printStackTrace(); } return ""; } Code Sample 2: public void deleteUser(final List<Integer> userIds) { try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.delete")); Iterator<Integer> iter = userIds.iterator(); int userId; while (iter.hasNext()) { userId = iter.next(); psImpl.setInt(1, userId); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUsers(userIds); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
11
Code Sample 1: static void invalidSlave(String msg, Socket sock) throws IOException { BufferedReader _sinp = null; PrintWriter _sout = null; try { _sout = new PrintWriter(sock.getOutputStream(), true); _sinp = new BufferedReader(new InputStreamReader(sock.getInputStream())); _sout.println(msg); logger.info("NEW< " + msg); String txt = SocketSlaveListener.readLine(_sinp, 30); String sname = ""; String spass = ""; String shash = ""; try { String[] items = txt.split(" "); sname = items[1].trim(); spass = items[2].trim(); shash = items[3].trim(); } catch (Exception e) { throw new IOException("Slave Inititalization Faailed"); } String pass = sname + spass + _pass; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(pass.getBytes()); String hash = SocketSlaveListener.hash2hex(md5.digest()).toLowerCase(); if (!hash.equals(shash)) { throw new IOException("Slave Inititalization Faailed"); } } catch (Exception e) { } throw new IOException("Slave Inititalization Faailed"); } Code Sample 2: public static String hashStringMD5(String string) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(string.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
00
Code Sample 1: private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) { if ((organizationName == null) || (organizationName.equals(""))) { message = "invalid new_organization_name."; return false; } String tmpxml = TextUtil.xmlEscape(organizationName); String tmpdb = DBAccess.SQLEscape(organizationName); if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) { message = "invalid new_organization_name."; return false; } if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) { message = "invalid new_organization_name."; return false; } String[] orgnames = ServerConsoleServlet.getOrganizationNames(); for (int i = 0; i < orgnames.length; i++) { if (orgnames.equals(organizationName)) { message = "already exists."; return false; } } message = "create new organization: " + organizationName; File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName); if (!newOrganizationDirectory.mkdir()) { message = "cannot create directory."; return false; } File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName")); cacheDir.mkdir(); File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName")); confDir.mkdir(); File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName")); rdfDir.mkdir(); File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName")); resourceDir.mkdir(); File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete"); obsoleteDir.mkdir(); File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName")); schemaDir.mkdir(); String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate")); File templ = new File(organization_temp_dir); File[] confFiles = templ.listFiles(); for (int i = 0; i < confFiles.length; i++) { try { FileReader fr = new FileReader(confFiles[i]); FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName()); int c = -1; while ((c = fr.read()) != -1) fw.write(c); fw.flush(); fw.close(); fr.close(); } catch (IOException e) { } } SchemaModelHolder.reloadSchemaModel(organizationName); ResourceModelHolder.reloadResourceModel(organizationName); UserLogServlet.initializeUserLogDB(organizationName); MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username); ResourceModelHolder.reloadResourceModel(organizationName); message = organizationName + " is created. Restart Tomcat to activate this organization."; return true; } Code Sample 2: protected void runTest(URL pBaseURL, String pName, String pHref) throws Exception { URL url = new URL(pBaseURL, pHref); XSParser parser = new XSParser(); parser.setValidating(false); InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toString()); String result; try { parser.parse(isource); ++numOk; result = "Ok"; } catch (Exception e) { ++numFailed; result = e.getMessage(); } log("Running test " + pName + " with URL " + url + ": " + result); }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private synchronized boolean saveU(URL url, String typeFlag, byte[] arrByte) { BufferedReader buffReader = null; BufferedOutputStream buffOS = null; URLConnection urlconnection = null; char flagChar = '0'; boolean flag = true; try { urlconnection = url.openConnection(); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); urlconnection.setUseCaches(false); urlconnection.setRequestProperty("Content-type", "application/octet-stream"); buffOS = new BufferedOutputStream(urlconnection.getOutputStream()); buffOS.write((byte[]) typeFlag.getBytes()); buffOS.write(arrByte); buffOS.flush(); if (Config.DEBUG) System.out.println("Applet output file successfully! "); buffReader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream())); StringBuffer stringBuff = new StringBuffer(); String serReturnMess = buffReader.readLine(); if (Config.DEBUG) System.out.println("Applet check status successfully! " + serReturnMess); flagChar = '2'; if (serReturnMess != null) { stringBuff.append(serReturnMess); serReturnMess = serReturnMess.substring(serReturnMess.indexOf(32)).trim() + '2'; flagChar = serReturnMess.charAt(0); } while ((serReturnMess = buffReader.readLine()) != null) { if (serReturnMess.length() <= 0) break; } } catch (Throwable e) { e.printStackTrace(); return false; } finally { try { if (buffOS != null) buffOS.close(); if (buffReader != null) buffReader.close(); } catch (Throwable e) { e.printStackTrace(); } if (flagChar == '2' || flagChar == '3') flag = true; else flag = false; } return flag; }
00
Code Sample 1: public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: private static void _readAllRegionMDFiles(ClassLoader loader, RegionMetadata bean, String regionMDFile) { if (_LOG.isFinest()) { _LOG.finest("searching for region-metadata with resource:{0}", regionMDFile); } try { Enumeration<URL> files = loader.getResources(regionMDFile); while (files.hasMoreElements()) { URL url = files.nextElement(); String publicId = url.toString(); try { InputStream in = url.openStream(); _readRegionMetadata(bean, in, publicId); in.close(); } catch (IOException e) { _error(publicId, e); } } } catch (IOException e) { _LOG.warning("ERR_GET_REGION_METADATA_FILE", __CONFIG_FILE_OTHER); _LOG.warning(e); } }
00
Code Sample 1: @Override public IMedium createMedium(String urlString, IMetadata optionalMetadata) throws MM4UCannotCreateMediumElementsException { Debug.println("createMedium(): URL: " + urlString); IAudio tempAudio = null; try { String cachedFileUri = null; try { URL url = new URL(urlString); InputStream is = url.openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); MediaCache cache = new MediaCache(); cachedFileUri = cache.addAudio(urlString, out).getURI().substring(5); } catch (MalformedURLException e) { cachedFileUri = urlString; } TAudioFileFormat fFormat = null; try { fFormat = (TAudioFileFormat) new MpegAudioFileReader().getAudioFileFormat(new File(cachedFileUri)); } catch (Exception e) { System.err.println("getAudioFileFormat() failed: " + e); } int length = Constants.UNDEFINED_INTEGER; if (fFormat != null) { length = Math.round(Integer.valueOf(fFormat.properties().get("duration").toString()).intValue() / 1000); } String mimeType = Utilities.getMimetype(Utilities.getURISuffix(urlString)); optionalMetadata.addIfNotNull(IMedium.MEDIUM_METADATA_MIMETYPE, mimeType); if (length != Constants.UNDEFINED_INTEGER) { tempAudio = new Audio(this, length, urlString, optionalMetadata); } } catch (Exception exc) { exc.printStackTrace(); return null; } return tempAudio; } Code Sample 2: private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public void getFile(String url, String filepath) throws BggException { System.out.println(url); int retry = retryCount + 1; lastURL = url; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; BufferedInputStream bis = null; OutputStream osw = null; try { con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); setHeaders(con); con.setRequestMethod("GET"); responseCode = con.getResponseCode(); bis = new BufferedInputStream(con.getInputStream()); int data; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filepath)); while ((data = bis.read()) != -1) bos.write(data); bos.flush(); bos.close(); break; } finally { try { bis.close(); } catch (Exception ignore) { } try { osw.close(); } catch (Exception ignore) { } try { con.disconnect(); } catch (Exception ignore) { } } } catch (IOException ioe) { if (responseCode == UNAUTHORIZED || responseCode == FORBIDDEN) { throw new BggException(ioe.getMessage(), responseCode); } if (retriedCount == retryCount) { throw new BggException(ioe.getMessage(), responseCode); } } try { Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { } } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void transfer(File src, File dest, boolean removeSrc) throws FileNotFoundException, IOException { Log.warning("source: " + src); Log.warning("dest: " + dest); if (!src.canRead()) { throw new IOException("can not read src file: " + src); } if (!dest.getParentFile().isDirectory()) { if (!dest.getParentFile().mkdirs()) { throw new IOException("failed to make directories: " + dest.getParent()); } } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); Log.warning("starting transfer from position " + fcin.position() + " to size " + fcin.size()); fcout.transferFrom(fcin, 0, fcin.size()); Log.warning("closing streams and channels"); fcin.close(); fcout.close(); fis.close(); fos.close(); if (removeSrc) { Log.warning("deleting file " + src); src.delete(); } }
11
Code Sample 1: private boolean handlePart(Part p) throws MessagingException, GetterException { String filename = p.getFileName(); if (!p.isMimeType("multipart/*")) { String disp = p.getDisposition(); if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (checkCriteria(p)) { if (filename == null) filename = "Attachment" + attnum++; if (result == null) { try { File f = File.createTempFile("amorph_pop3-", ".tmp"); f.deleteOnExit(); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); InputStream is = p.getInputStream(); int c; while ((c = is.read()) != -1) os.write(c); os.close(); result = new FileInputStream(f); System.out.println("saved attachment to file: " + f.getAbsolutePath()); return true; } catch (IOException ex) { throw new GetterException(ex, "Failed to save attachment: " + ex); } } } } } return false; } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
00
Code Sample 1: protected void load() throws IOException { for (ClassLoader classLoader : classLoaders) { Enumeration<URL> en = classLoader.getResources("META-INF/services/" + serviceClass.getName()); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStream in = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); try { String line = null; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { line = line.trim(); if (line.length() > 0) contributions.add(resolveClass(url, line)); } } } finally { reader.close(); } } finally { in.close(); } } } } Code Sample 2: private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
00
Code Sample 1: public static void main(String[] args) { String str = "vbnjm7pexhlmof3kapi_key76bbc056cf516a844af25a763b2b8426auth_tokenff8080812374bd3f0123b60363a5230acomment_text你frob118edb4cb78b439207c2329b76395f9fmethodyupoo.photos.comments.addphoto_idff80808123922c950123b6066c946a3f"; MessageDigest md = null; String s = new String("你"); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } md.reset(); try { md.update(str.getBytes("UTF-8")); System.out.println(new BigInteger(1, md.digest()).toString(16)); System.out.println(new BigInteger(1, s.getBytes("UTF-8")).toString(16)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Code Sample 2: private Callable<Request> newRequestCall(final Request request) { return new Callable<Request>() { public Request call() { InputStream is = null; try { if (DEBUG) Log.d(TAG, "Requesting: " + request.uri); HttpGet httpGet = new HttpGet(request.uri.toString()); httpGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = mHttpClient.execute(httpGet); String mimeType = response.getHeaders("Content-Type")[0].getValue(); if (DEBUG) Log.d(TAG, "mimeType:" + mimeType); if (mimeType.startsWith("image")) { HttpEntity entity = response.getEntity(); is = getUngzippedContent(entity); Bitmap bitmap = BitmapFactory.decodeStream(is); if (mResourceCache.store(request.hash, bitmap)) { mCache.put(request.uri.toString(), new SoftReference<Bitmap>(bitmap)); if (DEBUG) Log.d(TAG, "Request successful: " + request.uri); } else { mResourceCache.invalidate(request.hash); } } } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); } finally { if (DEBUG) Log.e(TAG, "Request finished: " + request.uri); mActiveRequestsMap.remove(request); if (is != null) { notifyObservers(request.uri); } try { if (is != null) { is.close(); } } catch (IOException e) { if (DEBUG) e.printStackTrace(); } } return request; } }; }
11
Code Sample 1: public static boolean copy(final File from, final File to) { if (from.isDirectory()) { to.mkdirs(); for (final String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { if (COPY_DEBUG) { System.out.println("Failed to copy " + name + " from " + from + " to " + to); } return false; } } } else { try { final FileInputStream is = new FileInputStream(from); final FileChannel ifc = is.getChannel(); final FileOutputStream os = makeFile(to); if (USE_NIO) { final FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (final IOException ex) { if (COPY_DEBUG) { System.out.println("Failed to copy " + from + " to " + to + ": " + ex); } return false; } } final long time = from.lastModified(); setLastModified(to, time); final long newtime = to.lastModified(); if (COPY_DEBUG) { if (newtime != time) { System.out.println("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime)); to.setLastModified(time); final long morenewtime = to.lastModified(); return false; } else { System.out.println("Timestamp for " + to + " set successfully."); } } return time == newtime; } Code Sample 2: public static void copy(File from, File to) { if (from.getAbsolutePath().equals(to.getAbsolutePath())) { return; } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(from); os = new FileOutputStream(to); int read = -1; byte[] buffer = new byte[10000]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } catch (Exception e) { throw new RuntimeException(); } finally { try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } }
11
Code Sample 1: public static final String crypt(final String password, String salt, final String magic) { if (password == null) throw new IllegalArgumentException("Null password!"); if (salt == null) throw new IllegalArgumentException("Null salt!"); if (magic == null) throw new IllegalArgumentException("Null salt!"); byte finalState[]; long l; MessageDigest ctx, ctx1; try { ctx = MessageDigest.getInstance("md5"); ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException ex) { System.err.println(ex); return null; } if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { ctx.update(finalState, 0, pl > 16 ? 16 : pl); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState, 0, 1); } else { ctx.update(password.getBytes(), 0, 1); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { try { ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException e0) { return null; } if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { ctx1.update(finalState, 0, 16); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { ctx1.update(finalState, 0, 16); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } final StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); } Code Sample 2: public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
00
Code Sample 1: public static String md5hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); return new BigInteger(1, digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { LOG.error(e); } return null; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public static final void copy(File src, File dest) throws IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; if (!src.exists()) { throw new IOException("Source not found: " + src); } if (!src.canRead()) { throw new IOException("Source is unreadable: " + src); } if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) { parentdir.mkdir(); } } else if (dest.isDirectory()) { dest = new File(dest + File.separator + src); } } else if (src.isDirectory()) { if (dest.isFile()) { throw new IOException("Cannot copy directory " + src + " to file " + dest); } if (!dest.exists()) { dest.mkdir(); } } if (src.isFile()) { try { source = new FileInputStream(src); destination = new FileOutputStream(dest); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) { break; } destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { } } if (destination != null) { try { destination.close(); } catch (IOException e) { } } } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target), new File(targetdest)); } else { try { source = new FileInputStream(target); destination = new FileOutputStream(targetdest); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) { break; } destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { } } if (destination != null) { try { destination.close(); } catch (IOException e) { } } } } } } } Code Sample 2: protected InputSource getInputSource(String pReferencingSystemId, String pURI) throws SAXException { URL url = null; if (pReferencingSystemId != null) { try { url = new URL(new URL(pReferencingSystemId), pURI); } catch (MalformedURLException e) { } if (url == null) { try { url = new File(new File(pReferencingSystemId).getParentFile(), pURI).toURL(); } catch (MalformedURLException e) { } } } if (url == null) { try { url = new URL(pURI); } catch (MalformedURLException e) { try { url = new File(pURI).toURL(); } catch (MalformedURLException f) { throw new SAXException("Failed to parse the URI " + pURI); } } } try { InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toString()); return isource; } catch (IOException e) { throw new SAXException("Failed to open the URL " + url, e); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; }
00
Code Sample 1: private void dealWith(String line) throws Exception { if (line.startsWith("#") || (line.length() == 0)) { return; } String sarr[]; sarr = StringUtil.split(line, '\t'); String path = destDir + File.separator + sarr[0]; boolean copyFile = true; if (sarr.length == 2) { try { String serverHash = sarr[1]; String fileHash = loadFileHash(destDir + File.separator + sarr[0]); if (fileHash != null) { if (serverHash.equalsIgnoreCase(fileHash)) { copyFile = false; } else { if (verbose) { System.out.println(" -- " + sarr[0] + " has changed"); } } } } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); System.exit(2); } } if (copyFile) { int idx = path.lastIndexOf('/'); if (idx > 0) { String dir = path.substring(0, idx); File f = new File(dir); f.mkdirs(); } FileOutputStream os = new FileOutputStream(path); byte buf[] = new byte[1024]; URLConnection urc = new URL(urlStr + "/" + sarr[0]).openConnection(); InputStream is = urc.getInputStream(); boolean done = false; while (!done) { int read = is.read(buf, 0, 1024); if (read == -1) { done = true; } else { os.write(buf, 0, read); } } os.close(); is.close(); if (verbose) { System.out.println(" -- Copied: " + sarr[0]); } } } Code Sample 2: public static String hash(String plainText) throws Exception { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(plainText.getBytes(), 0, plainText.length()); String hash = new BigInteger(1, m.digest()).toString(16); if (hash.length() == 31) { hash = "0" + hash; } return hash; }
00
Code Sample 1: protected List<? extends SearchResult> searchVideo(String words, int number, int offset, CancelMonitor cancelMonitor) { List<VideoSearchResult> resultsList = new ArrayList<>(); try { // set up the HTTP request factory HttpTransport transport = new NetHttpTransport(); HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { // set the parser JsonCParser parser = new JsonCParser(); parser.jsonFactory = JSON_FACTORY; request.addParser(parser); // set up the Google headers GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("OGLExplorer/1.0"); headers.gdataVersion = "2"; request.headers = headers; } }); // build the YouTube URL YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos"); url.maxResults = number; url.words = words; url.startIndex = offset + 1; // build HttpRequest request = factory.buildGetRequest(url); // execute HttpResponse response = request.execute(); VideoFeed feed = response.parseAs(VideoFeed.class); if (feed.items == null) { return null; } // browse result and convert them to the local generic object model for (int i = 0; i < feed.items.size() && !cancelMonitor.isCanceled(); i++) { Video result = feed.items.get(i); VideoSearchResult modelResult = new VideoSearchResult(offset + i + 1); modelResult.setTitle(result.title); modelResult.setDescription(result.description); modelResult.setThumbnailURL(new URL(result.thumbnail.lowThumbnailURL)); modelResult.setPath(result.player.defaultUrl); resultsList.add(modelResult); } } catch (Exception e) { e.printStackTrace(); } if (cancelMonitor.isCanceled()) { return null; } return resultsList; } Code Sample 2: public static String getInstanceUserdata() throws IOException { int retries = 0; while (true) { try { URL url = new URL("http://169.254.169.254/latest/user-data/"); InputStreamReader rdr = new InputStreamReader(url.openStream()); StringWriter wtr = new StringWriter(); char[] buf = new char[1024]; int bytes; while ((bytes = rdr.read(buf)) > -1) { if (bytes > 0) { wtr.write(buf, 0, bytes); } } rdr.close(); return wtr.toString(); } catch (IOException ex) { if (retries == 5) { logger.debug("Problem getting user data, retries exhausted..."); return null; } else { logger.debug("Problem getting user data, retrying..."); try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException e) { } retries++; } } } }
11
Code Sample 1: public static byte[] generateAuthId(String userName, String password) { byte[] ret = new byte[16]; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); String str = userName + password; messageDigest.update(str.getBytes()); ret = messageDigest.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return ret; } Code Sample 2: public byte[] encryptMsg(String encryptString) { byte[] encryptByte = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(encryptString.getBytes()); encryptByte = messageDigest.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return encryptByte; }
00
Code Sample 1: public ViewedCandidates postViewedCandidates(ViewedCandidates viewedCandidates) throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpPost req = new HttpPost(remoteHost.getUrl() + "/cand/viewed"); req.setHeader("Accept-Encoding", "gzip"); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); XMLWriter.write(out, viewedCandidates); ByteArrayInputStream in2 = new ByteArrayInputStream(out.toByteArray()); req.setEntity(new InputStreamEntity(in2, -1)); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof ViewedCandidates) { ViewedCandidates p = (ViewedCandidates) xmlable; return p; } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for ViewedCandidates"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } } Code Sample 2: private static void stampaFoglioRisposte(HttpSession httpSess, Appelli appello, Elaborati el, StringBuffer retVal, boolean primaVolta, String url, boolean anonimo) { InputStream is = null; String html = null; final int MAX_RIGHE_PER_PAGINA = 25; long totaleDomande = EsamiDAO.trovaQuanteDomandeElaborato(el.getID()); long numPagine = 0, totalePagine = (long) Math.ceil(totaleDomande / 50.0); String urlBarcode = null; while (numPagine < totalePagine) { try { urlBarcode = URLEncoder.encode(HtmlCodeForPrint.creaBarcode("" + appello.getID() + "-" + el.getID() + "-" + (numPagine + 1), url), "UTF-8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); } String jsp = url + "jsp/StampaRisposte.jsp?base=" + (numPagine * MAX_RIGHE_PER_PAGINA) + "&urlbarcode=" + urlBarcode; try { URL urlJSP = new URL(jsp); is = urlJSP.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int letto = is.read(); while (letto != -1) { baos.write(letto); letto = is.read(); } html = baos.toString(); } catch (IOException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } finally { try { is.close(); } catch (IOException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); } numPagine++; } } retVal.append(html); }
00
Code Sample 1: @Override public void onLoadingEnded() { if (m_frame != null) { try { String urltext = getDocument().getDocumentURI(); URL url = new URL(urltext); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader in = new BufferedReader(isr); String inputLine; urltext = null; url = null; m_content.clear(); while ((inputLine = in.readLine()) != null) { m_content.add(inputLine); } in.close(); isr = null; in = null; inputLine = null; Action action = parseHtml(); if (action.value() == Action.ACTION_BROWSER_LOADING_DONE && action.toString().equals(Action.COMMAND_CARD_PREVIEW)) { FileUtils.copyURLToFile(new URL(getCardImageURL(m_card.MID)), new File(m_card.getImagePath())); fireActionEvent(MainWindow.class, action.value(), action.toString()); } action = null; } catch (Exception ex) { Dialog.ErrorBox(m_frame, ex.getStackTrace()); } } m_loading = false; } Code Sample 2: public void buildCache() { XMLCacheBuilder cacheBuilder = CompositePageUtil.getCacheBuilder(); String postFix = ""; if (cacheBuilder.getPostFix() != null && !cacheBuilder.getPostFix().equals("")) { postFix = "." + cacheBuilder.getPostFix(); } String basePath = cacheBuilder.getBasePath(); List actions = CompositePageUtil.getXMLActions(); for (int i = 0; i < actions.size(); i++) { try { XMLAction action = (XMLAction) actions.get(i); if (action.getEscapeCacheBuilder() != null && action.getEscapeCacheBuilder().equals("true")) continue; String actionUrl = basePath + action.getName() + postFix; URL url = new URL(actionUrl); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setDoInput(true); huc.setDoOutput(true); huc.setUseCaches(false); huc.setRequestProperty("Content-Type", "text/html"); DataOutputStream dos = new DataOutputStream(huc.getOutputStream()); dos.flush(); dos.close(); huc.disconnect(); } catch (MalformedURLException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.equals(e); e.printStackTrace(); } } }
00
Code Sample 1: public DataSet guessAtUnknowns(String filename) { TasselFileType guess = TasselFileType.Sequence; DataSet tds = null; try { BufferedReader br = null; if (filename.startsWith("http")) { URL url = new URL(filename); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { br = new BufferedReader(new FileReader(filename)); } String line1 = br.readLine().trim(); String[] sval1 = line1.split("\\s"); String line2 = br.readLine().trim(); String[] sval2 = line2.split("\\s"); boolean lociMatchNumber = false; if (!sval1[0].startsWith("<") && (sval1.length == 2) && (line1.indexOf(':') < 0)) { int countLoci = Integer.parseInt(sval1[1]); if (countLoci == sval2.length) { lociMatchNumber = true; } } if (sval1[0].equalsIgnoreCase("<Annotated>")) { guess = TasselFileType.Annotated; } else if (line1.startsWith("<") || line1.startsWith("#")) { boolean isTrait = false; boolean isMarker = false; boolean isNumeric = false; boolean isMap = false; Pattern tagPattern = Pattern.compile("[<>\\s]+"); String[] info1 = tagPattern.split(line1); String[] info2 = tagPattern.split(line2); if (info1.length > 1) { if (info1[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info1[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info1[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info1[1].toUpperCase().startsWith("MAP")) { isMap = true; } } if (info2.length > 1) { if (info2[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info2[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info2[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info2[1].toUpperCase().startsWith("MAP")) { isMap = true; } } else { guess = null; String inline = br.readLine(); while (guess == null && inline != null && (inline.startsWith("#") || inline.startsWith("<"))) { if (inline.startsWith("<")) { String[] info = tagPattern.split(inline); if (info[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info[1].toUpperCase().startsWith("MAP")) { isMap = true; } } } } if (isTrait || (isMarker && isNumeric)) { guess = TasselFileType.Phenotype; } else if (isMarker) { guess = TasselFileType.Polymorphism; } else if (isMap) { guess = TasselFileType.GeneticMap; } else { throw new IOException("Improperly formatted header. Data will not be imported."); } } else if ((line1.startsWith(">")) || (line1.startsWith(";"))) { guess = TasselFileType.Fasta; } else if (sval1.length == 1) { guess = TasselFileType.SqrMatrix; } else if (line1.indexOf(':') > 0) { guess = TasselFileType.Polymorphism; } else if ((sval1.length == 2) && (lociMatchNumber)) { guess = TasselFileType.Polymorphism; } else if ((line1.startsWith("#Nexus")) || (line1.startsWith("#NEXUS")) || (line1.startsWith("CLUSTAL")) || ((sval1.length == 2) && (sval2.length == 2))) { guess = TasselFileType.Sequence; } else if (sval1.length == 3) { guess = TasselFileType.Numerical; } myLogger.info("guessAtUnknowns: type: " + guess); tds = processDatum(filename, guess); br.close(); } catch (Exception e) { } return tds; } Code Sample 2: public void testScenario() throws Exception { String expression = "SELECT id, name, address, phone FROM " + TABLE + " where id > 2 and id < 12 order by id"; SQLQuery query = new SQLQuery(); query.setResourceID(mResourceID); query.addExpression(expression); TupleToWebRowSetCharArrays tupleToWebRowSet = new TupleToWebRowSetCharArrays(); tupleToWebRowSet.connectDataInput(query.getDataOutput()); DeliverToFTP deliverToFTP = new DeliverToFTP(); deliverToFTP.connectDataInput(tupleToWebRowSet.getResultOutput()); deliverToFTP.addFilename(FILE); deliverToFTP.addHost(mURL); PipelineWorkflow pipeline = new PipelineWorkflow(); pipeline.add(query); pipeline.add(tupleToWebRowSet); pipeline.add(deliverToFTP); mDRER.execute(pipeline, RequestExecutionType.SYNCHRONOUS); final URL url = new URL("ftp://" + mURL + "/" + FILE); final URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); InputStream is = connection.getInputStream(); WebRowSetToResultSet converter = new WebRowSetToResultSet(new InputStreamReader(is)); converter.setResultSetType(ResultSet.TYPE_FORWARD_ONLY); ResultSet rs = converter.getResultSet(); JDBCTestHelper.validateResultSet(mConnection, expression, rs, 1); rs.close(); }
11
Code Sample 1: public static File copyFile(File file, String dirName) { File destDir = new File(dirName); if (!destDir.exists() || !destDir.isDirectory()) { destDir.mkdirs(); } File src = file; File dest = new File(dirName, src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } Code Sample 2: public void checkFilesAndCopyValid(String filename) { downloadResults(); loadResults(); File tmpFolderF = new File(tmpFolder); deleteFileFromTMPFolder(tmpFolderF); ZipReader zr = new ZipReader(); zr.UnzipFile(filename); try { LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:"); LogManager.getInstance().log(""); JAXBElement<?> element = ElementJAXB.getJAXBElement(); Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue(); File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0]; File[] zipFolderList = zipFolder.listFiles(); for (File studentDirectory : zipFolderList) { if (studentDirectory.isDirectory()) { String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0]; LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky); List<StudentType> students = (List<StudentType>) pvct.getStudent(); for (StudentType student : students) { if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) { int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue(); DomaciUlohyType dut = student.getDomaciUlohy(); ChybneOdevzdaneType chot = dut.getChybneOdevzdane(); ObjectFactory of = new ObjectFactory(); File[] pokusyDirectories = studentDirectory.listFiles(); NodeList souboryNL = result.getElementsByTagName("soubor"); int start = souboryNL.getLength() - 1; boolean samostatnaPrace = false; for (int i = (pokusyDirectories.length - 1); i >= 0; i--) { if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) { File testedFile = pokusyDirectories[i].listFiles()[0]; if ((testedFile.exists()) && (testedFile.isFile())) { String[] partsOfFilename = testedFile.getName().split("_"); String osobniCisloZeSouboru = "", priponaSouboru = ""; String[] posledniCastSouboru = null; if (partsOfFilename.length == 4) { posledniCastSouboru = partsOfFilename[3].split("[.]"); osobniCisloZeSouboru = posledniCastSouboru[0]; if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1]; } String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev(); List<SouborType> lst = chot.getSoubor(); if (testedFile.getName().startsWith(samostatnaPraceNazev)) { samostatnaPrace = true; } else { samostatnaPrace = false; if (partsOfFilename.length != 4) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� struktura jm�na souboru."); lst.add(st); continue; } else if (!testedFile.getName().startsWith("Ppa1_cv")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� za��tek jm�na souboru."); lst.add(st); continue; } else if (!priponaSouboru.equals("java")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� p��pona souboru."); lst.add(st); continue; } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Nesouhlas� osobn� ��sla."); lst.add(st); continue; } else if (partsOfFilename[3].split("[.]").length > 2) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("V�ce p��pon souboru."); lst.add(st); continue; } else { long cisloCviceni, cisloUlohy; try { if (partsOfFilename[1].length() == 4) { String cisloS = partsOfFilename[1].substring(2); long cisloL = Long.parseLong(cisloS); cisloCviceni = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�"); lst.add(st); continue; } try { if (partsOfFilename[2].length() > 0) { String cisloS = partsOfFilename[2]; long cisloL = Long.parseLong(cisloS); cisloUlohy = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy"); lst.add(st); continue; } CislaUloh ci = new CislaUloh(); List<long[]> cviceni = ci.getSeznamCviceni(); boolean nalezenoCv = false, nalezenaUl = false; for (long[] c : cviceni) { if (c[0] == cisloCviceni) { for (int j = 1; j < c.length; j++) { if (c[j] == cisloUlohy) { nalezenaUl = true; break; } } nalezenoCv = true; break; } } if (!nalezenoCv) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo cvi�en�"); lst.add(st); continue; } if (!nalezenaUl) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo �lohy"); lst.add(st); continue; } } } } Calendar dateFromZipFile = null; File zipFile = new File(filename); if (zipFile.exists()) { String[] s = zipFile.getName().split("_"); if (s.length >= 3) { String[] date = s[1].split("-"), time = s[2].split("-"); dateFromZipFile = new GregorianCalendar(); dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0); } } boolean shodaJmenaSouboru = false; String vysledekValidaceSouboru = ""; for (int j = start; j >= 0; j--) { NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes(); for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) { if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) { String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" "); String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-"); Calendar datumACasZElementu = new GregorianCalendar(); datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2])); if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) { shodaJmenaSouboru = false; break; } } if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) { shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName()); } if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) { vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent(); } } if (shodaJmenaSouboru) { start = --j; break; } } if (shodaJmenaSouboru && !samostatnaPrace) { boolean odevzdanoVcas = false; String cisloCviceniS = testedFile.getName().split("_")[1].substring(2); int cisloCviceniI = Integer.parseInt(cisloCviceniS); String cisloUlohyS = testedFile.getName().split("_")[2]; int cisloUlohyI = Integer.parseInt(cisloUlohyS); List<CviceniType> lct = student.getDomaciUlohy().getCviceni(); for (CviceniType ct : lct) { if (ct.getCislo().intValue() == cisloCviceniI) { MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas(); Calendar mtovGC = new GregorianCalendar(); mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59); Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false; List<UlohaType> lut = ct.getUloha(); for (UlohaType ut : lut) { if (ut.getCislo().intValue() == cisloUlohyI) { List<OdevzdanoType> lot = ut.getOdevzdano(); OdevzdanoType ot = of.createOdevzdanoType(); ot.setDatum(xmlGCDate); ot.setCas(xmlGCTime); OdevzdanoVcasType ovt = of.createOdevzdanoVcasType(); ovt.setVysledek(odevzdanoVcas); ValidatorType vt = of.createValidatorType(); vt.setVysledek(vysledekValidaceSouboru.equals("true")); ot.setOdevzdanoVcas(ovt); ot.setValidator(vt); lot.add(ot); if (vt.isVysledek()) { String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue()); if (!(new File(test).exists())) { LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + "."); return; } else { copyValidFile(testedFile, ct.getCislo().intValue()); } } break; } } break; } } } else if (shodaJmenaSouboru && samostatnaPrace) { String[] partsOfFilename = testedFile.getName().split("_"); String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]"); String osobniCisloZeSouboru = partsOfLastPartOfFilename[0]; String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1]; if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) { if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) { Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno(); if (lut.isEmpty()) { File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName()); if (samostatnaPraceNewFile.exists()) { samostatnaPraceNewFile.delete(); samostatnaPraceNewFile.createNewFile(); } String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(testedFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(samostatnaPraceNewFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); samostatnaPraceNewFile.setLastModified(testedFile.lastModified()); } UlozenoType ut = of.createUlozenoType(); ut.setDatum(xmlGCDate); ut.setCas(xmlGCTime); lut.add(0, ut); } } } } } PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType(); String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_"); int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim()); pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu))); student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt); break; } } } } ElementJAXB.setJAXBElement(element); LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno."); } catch (FileNotFoundException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (DatatypeConfigurationException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ..."); deleteFileFromTMPFolder(tmpFolderF); LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK"); }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
11
Code Sample 1: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } Code Sample 2: private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
11
Code Sample 1: @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 { tmpFile = File.createTempFile("ftp", "dat", new File("./tmp")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); IOUtils.copy(is, bos); bos.flush(); bos.close(); } 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); } } Code Sample 2: 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(); }
11
Code Sample 1: protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } Code Sample 2: public static String translate(String s) { try { String result = null; URL url = new URL("http://translate.google.com/translate_t"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("text=" + URLEncoder.encode(s, "UTF-8") + "&langpair="); if (s.matches("[\\u0000-\\u00ff]+")) { out.print("en|ja"); } else { out.print("ja|en"); } out.print("&hl=en&ie=UTF-8&oe=UTF-8"); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("id=result_box"); if (textPos >= 0) { int ltrPos = inputLine.indexOf("dir=ltr", textPos + 9); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 8); if (closePos >= 0) { result = inputLine.substring(ltrPos + 8, closePos); } } } } in.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static void copyFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } Code Sample 2: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; }
11
Code Sample 1: public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void copyURLToFile(URL source, File destination) throws IOException { if (destination.getParentFile() != null && !destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } if (destination.exists() && !destination.canWrite()) { String message = "Unable to open file " + destination + " for writing."; throw new IOException(message); } InputStream input = source.openStream(); try { FileOutputStream output = new FileOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
00
Code Sample 1: public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken2", "password")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } Code Sample 2: public static String generateStringSHA256(String content) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ScannerChecksum.class.getName()).log(Level.SEVERE, null, ex); } md.update(content.getBytes()); byte byteData[] = md.digest(); @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
11
Code Sample 1: public void copyFileFromLocalMachineToRemoteMachine(InputStream source, File destination) throws Exception { String fileName = destination.getPath(); File f = new File(getFtpServerHome(), "" + System.currentTimeMillis()); f.deleteOnExit(); org.apache.commons.io.IOUtils.copy(source, new FileOutputStream(f)); remoteHostClient.setAscii(isAscii()); remoteHostClient.setPromptOn(isPrompt()); remoteHostClient.copyFileFromLocalMachineToRemoteClient(f.getName(), fileName); } Code Sample 2: @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(); } } }
11
Code Sample 1: public GEItem lookup(final String itemName) { try { URL url = new URL(GrandExchange.HOST + "/m=itemdb_rs/results.ws?query=" + itemName + "&price=all&members="); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; while ((input = br.readLine()) != null) { if (input.contains("<div id=\"search_results_text\">")) { input = br.readLine(); if (input.contains("Your search for")) { return null; } } else if (input.startsWith("<td><img src=")) { Matcher matcher = GrandExchange.PATTERN.matcher(input); if (matcher.find()) { if (matcher.group(2).contains(itemName)) { return lookup(Integer.parseInt(matcher.group(1))); } } } } } catch (IOException ignored) { } return null; } Code Sample 2: private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; }
11
Code Sample 1: @Deprecated public static void getAndProcessContents(String videoPageURL, int bufsize, String charset, Closure<String> process) throws IOException { URL url = null; HttpURLConnection connection = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { url = new URL(videoPageURL); connection = (HttpURLConnection) url.openConnection(); is = connection.getInputStream(); isr = new InputStreamReader(is, charset); br = new BufferedReader(isr); for (String line = br.readLine(); line != null; line = br.readLine()) { process.exec(line); } } finally { Closeables.closeQuietly(br); Closeables.closeQuietly(isr); Closeables.closeQuietly(is); HttpUtils.disconnect(connection); } } Code Sample 2: @Override public void loadData() { try { String url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=11&f=2099&g=d&ignore=.csv"; URLConnection conn = (new URL(url)).openConnection(); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); String str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double open = Double.parseDouble(split[1]); final double high = Double.parseDouble(split[2]); final double low = Double.parseDouble(split[3]); final double close = Double.parseDouble(split[4]); final int volume = Integer.parseInt(split[5]); final double adjClose = Double.parseDouble(split[6]); final HistoricalPrice price = new HistoricalPrice(date, open, high, low, close, volume, adjClose); historicalPrices.add(price); } in.close(); url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=17&f=2008&g=v&ignore=.csv"; conn = (new URL(url)).openConnection(); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double amount = Double.parseDouble(split[1]); final Dividend dividend = new Dividend(date, amount); dividends.add(dividend); } in.close(); } catch (final IOException ioe) { logger.error("Error parsing historical prices for " + getSymbol(), ioe); } }
11
Code Sample 1: private List<String> getHashesFrom(String webPage) { Vector<String> out = new Vector(); try { URL url = new URL(webPage); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = r.readLine()) != null) { out.add(line); } } catch (Exception X) { return null; } return out; } Code Sample 2: public static void readShaderSource(ClassLoader context, String path, URL url, StringBuffer result) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { if (line.startsWith("#include ")) { String includeFile = line.substring(9).trim(); String next = Locator.getRelativeOf(path, includeFile); URL nextURL = Locator.getResource(next, context); if (nextURL == null) { next = includeFile; nextURL = Locator.getResource(next, context); } if (nextURL == null) { throw new FileNotFoundException("Can't find include file " + includeFile); } readShaderSource(context, next, nextURL, result); } else { result.append(line + "\n"); } } } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setInt(2, q.getDisciplina().getIdDisciplina()); stmt.setInt(3, idTopico); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
00
Code Sample 1: private static String hashPassword(String password) { try { String hashword = null; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); return hashword; } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } } Code Sample 2: 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(); }
00
Code Sample 1: public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); } Code Sample 2: void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
11
Code Sample 1: private void post(String title, Document content, Set<String> tags) throws HttpException, IOException, TransformerException { PostMethod method = null; try { method = new PostMethod("http://www.blogger.com/feeds/" + this.blogId + "/posts/default"); method.addRequestHeader("GData-Version", String.valueOf(GDataVersion)); method.addRequestHeader("Authorization", "GoogleLogin auth=" + this.AuthToken); Document dom = this.domBuilder.newDocument(); Element entry = dom.createElementNS(Atom.NS, "entry"); dom.appendChild(entry); entry.setAttribute("xmlns", Atom.NS); Element titleNode = dom.createElementNS(Atom.NS, "title"); entry.appendChild(titleNode); titleNode.setAttribute("type", "text"); titleNode.appendChild(dom.createTextNode(title)); Element contentNode = dom.createElementNS(Atom.NS, "content"); entry.appendChild(contentNode); contentNode.setAttribute("type", "xhtml"); contentNode.appendChild(dom.importNode(content.getDocumentElement(), true)); for (String tag : tags) { Element category = dom.createElementNS(Atom.NS, "category"); category.setAttribute("scheme", "http://www.blogger.com/atom/ns#"); category.setAttribute("term", tag); entry.appendChild(category); } StringWriter out = new StringWriter(); this.xml2ascii.transform(new DOMSource(dom), new StreamResult(out)); method.setRequestEntity(new StringRequestEntity(out.toString(), "application/atom+xml", "UTF-8")); int status = getHttpClient().executeMethod(method); if (status == 201) { IOUtils.copyTo(method.getResponseBodyAsStream(), System.out); } else { throw new HttpException("post returned http-code=" + status + " expected 201 (CREATE)"); } } catch (TransformerException err) { throw err; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } } Code Sample 2: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
00
Code Sample 1: InputStream createInputStream(FileInfo fi) throws IOException, MalformedURLException { if (fi.inputStream != null) return fi.inputStream; else if (fi.url != null && !fi.url.equals("")) return new URL(fi.url + fi.fileName).openStream(); else { File f = new File(fi.directory + fi.fileName); if (f == null || f.isDirectory()) return null; else { InputStream is = new FileInputStream(f); if (fi.compression >= FileInfo.LZW) is = new RandomAccessStream(is); return is; } } } Code Sample 2: @Test public void config() throws IOException { Reader reader = new FileReader(new File("src/test/resources/test.yml")); Writer writer = new FileWriter(new File("src/site/apt/config.apt")); writer.write("------\n"); writer.write(FileUtils.readFully(reader)); writer.flush(); writer.close(); }
00
Code Sample 1: public void setInput(String input, Component caller, FFMpegProgressReceiver recv) throws IOException { inputMedium = null; if (input.contains("youtube")) { URL url = new URL(input); InputStreamReader read = new InputStreamReader(url.openStream()); BufferedReader in = new BufferedReader(read); String inputLine; String line = null; String vid = input.substring(input.indexOf("?v=") + 3); if (vid.indexOf("&") != -1) vid = vid.substring(0, vid.indexOf("&")); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("\"t\": \"")) { line = inputLine.substring(inputLine.indexOf("\"t\": \"") + 6); line = line.substring(0, line.indexOf("\"")); break; } } in.close(); if (line == null) throw new IOException("Could not find flv-Video"); Downloader dl = new Downloader("http://www.youtube.com/get_video?video_id=" + vid + "&t=" + line, recv, lang); dl.start(); return; } Runtime rt = Runtime.getRuntime(); Process p = rt.exec(new String[] { path, "-i", input }); BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; Codec videoCodec = null; Codec audioCodec = null; double duration = -1; String aspectRatio = null; String scala = null; String colorSpace = null; String rate = null; String mrate = null; String aRate = null; String aFreq = null; String aChannel = null; try { while ((line = br.readLine()) != null) { if (Constants.debug) System.out.println(line); if (line.contains("Duration:")) { int hours = Integer.parseInt(line.substring(12, 14)); int mins = Integer.parseInt(line.substring(15, 17)); double secs = Double.parseDouble(line.substring(18, line.indexOf(','))); duration = secs + 60 * mins + hours * 60 * 60; Pattern pat = Pattern.compile("[0-9]+ kb/s"); Matcher m = pat.matcher(line); if (m.find()) mrate = line.substring(m.start(), m.end()); } if (line.contains("Video:")) { String info = line.substring(24); String parts[] = info.split(", "); Pattern pat = Pattern.compile("Video: [a-zA-Z0-9]+,"); Matcher m = pat.matcher(line); String codec = ""; if (m.find()) codec = line.substring(m.start(), m.end()); videoCodec = supportedCodecs.getCodecByName(codec.replace("Video: ", "").replace(",", "")); colorSpace = parts[1]; pat = Pattern.compile("[0-9]+x[0-9]+"); m = pat.matcher(info); if (m.find()) scala = info.substring(m.start(), m.end()); pat = Pattern.compile("DAR [0-9]+:[0-9]+"); m = pat.matcher(info); if (m.find()) aspectRatio = info.substring(m.start(), m.end()).replace("DAR ", ""); else if (scala != null) aspectRatio = String.valueOf((double) (Math.round(((double) ConvertUtils.getWidthFromScala(scala) / (double) ConvertUtils.getHeightFromScala(scala)) * 100)) / 100); pat = Pattern.compile("[0-9]+ kb/s"); m = pat.matcher(info); if (m.find()) rate = info.substring(m.start(), m.end()); } else if (line.contains("Audio:")) { String info = line.substring(24); Pattern pat = Pattern.compile("Audio: [a-zA-Z0-9]+,"); Matcher m = pat.matcher(line); String codec = ""; if (m.find()) codec = line.substring(m.start(), m.end()).replace("Audio: ", "").replace(",", ""); if (codec.equals("mp3")) codec = "libmp3lame"; audioCodec = supportedCodecs.getCodecByName(codec); pat = Pattern.compile("[0-9]+ kb/s"); m = pat.matcher(info); if (m.find()) aRate = info.substring(m.start(), m.end()); pat = Pattern.compile("[0-9]+ Hz"); m = pat.matcher(info); if (m.find()) aFreq = info.substring(m.start(), m.end()); if (line.contains("5.1")) aChannel = "5.1"; else if (line.contains("2.1")) aChannel = "2.1"; else if (line.contains("stereo")) aChannel = "Stereo"; else if (line.contains("mono")) aChannel = "Mono"; } if (videoCodec != null && audioCodec != null && duration != -1) { if (rate == null && mrate != null && aRate != null) rate = String.valueOf(ConvertUtils.getRateFromRateString(mrate) - ConvertUtils.getRateFromRateString(aRate)) + " kb/s"; inputMedium = new InputMedium(audioCodec, videoCodec, input, duration, colorSpace, aspectRatio, scala, rate, mrate, aRate, aFreq, aChannel); break; } } if ((videoCodec != null || audioCodec != null) && duration != -1) inputMedium = new InputMedium(audioCodec, videoCodec, input, duration, colorSpace, aspectRatio, scala, rate, mrate, aRate, aFreq, aChannel); } catch (Exception exc) { if (caller != null) JOptionPane.showMessageDialog(caller, lang.inputerror + " Audiocodec? " + (audioCodec != null) + " Videocodec? " + (videoCodec != null), lang.error, JOptionPane.ERROR_MESSAGE); if (Constants.debug) System.out.println("Audiocodec: " + audioCodec + "\nVideocodec: " + videoCodec); if (Constants.debug) exc.printStackTrace(); throw new IOException("Input file error"); } if (inputMedium == null) { if (caller != null) JOptionPane.showMessageDialog(caller, lang.inputerror + " Audiocodec? " + (audioCodec != null) + " Videocodec? " + (videoCodec != null), lang.error, JOptionPane.ERROR_MESSAGE); if (Constants.debug) System.out.println("Audiocodec: " + audioCodec + "\nVideocodec: " + videoCodec); throw new IOException("Input file error"); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public void validateXml(InputStream inputData, ErrorHandler errorHandler) throws SAXException, IOException, Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(false); spf.setNamespaceAware(true); try { SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); URL schemaURL = new URL(schemeUrl); InputStream urlStream = null; try { urlStream = schemaURL.openStream(); } catch (IOException ex) { if (defaultUrl != null) { schemaURL = new URL(defaultUrl); urlStream = schemaURL.openStream(); } else { throw ex; } } LOGGER.debug("Uses schema url : " + schemaURL); StreamSource sss = new StreamSource(urlStream); Schema schema = schemaFactory.newSchema(sss); spf.setSchema(schema); SAXParser parser = spf.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(errorHandler); reader.parse(new InputSource(inputData)); } catch (ParserConfigurationException e) { throw new SAXException(e); } } Code Sample 2: protected PersistenceUnitInfo getPersistenceUnitInfo() { if (this.persistenceUnitInfo == null) { this.persistenceUnitInfo = new PersistenceUnitInfo() { private List<ClassTransformer> transformers; private List<String> managedClasses; private List<String> mappingFileNames; private ClassLoader classLoader; public String getPersistenceUnitName() { return "jomc-standalone"; } public String getPersistenceProviderClassName() { return getPersistenceProvider().getClass().getName(); } public PersistenceUnitTransactionType getTransactionType() { return PersistenceUnitTransactionType.JTA; } public DataSource getJtaDataSource() { try { return (DataSource) getContext().lookup(getEnvironment().getJtaDataSourceJndiName()); } catch (final NamingException e) { getLogger().fatal(e); throw new RuntimeException(e); } } public DataSource getNonJtaDataSource() { return null; } public List<String> getMappingFileNames() { try { if (this.mappingFileNames == null) { this.mappingFileNames = new LinkedList<String>(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); for (final Enumeration<URL> e = this.getNewTempClassLoader().getResources("META-INF/persistence.xml"); e.hasMoreElements(); ) { final URL url = e.nextElement(); final InputStream in = url.openStream(); final Document doc = documentBuilder.parse(in); in.close(); final NodeList persistenceUnits = doc.getElementsByTagNameNS(PERSISTENCE_NS, "persistence-unit"); for (int i = persistenceUnits.getLength() - 1; i >= 0; i--) { final Element persistenceUnit = (Element) persistenceUnits.item(i); final NodeList mappingFiles = persistenceUnit.getElementsByTagNameNS(PERSISTENCE_NS, "mapping-file"); for (int j = mappingFiles.getLength() - 1; j >= 0; j--) { final Element mappingFile = (Element) mappingFiles.item(j); this.mappingFileNames.add(mappingFile.getFirstChild().getNodeValue()); } } } } return this.mappingFileNames; } catch (final SAXException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final IOException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final ParserConfigurationException e) { getLogger().fatal(e); throw new RuntimeException(e); } } public List<URL> getJarFileUrls() { try { final List<URL> jarFileUrls = new LinkedList<URL>(); for (final Enumeration<URL> unitUrls = this.getClassLoader().getResources("META-INF/persistence.xml"); unitUrls.hasMoreElements(); ) { final URL unitUrl = unitUrls.nextElement(); final String externalForm = unitUrl.toExternalForm(); final String jarUrl = externalForm.substring(0, externalForm.indexOf("META-INF")); jarFileUrls.add(new URL(jarUrl)); } return jarFileUrls; } catch (final IOException e) { getLogger().fatal(e); throw new RuntimeException(e.getMessage(), e); } } public URL getPersistenceUnitRootUrl() { return getEnvironment().getJpaRootUrl(); } public List<String> getManagedClassNames() { try { if (this.managedClasses == null) { this.managedClasses = new LinkedList<String>(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); for (final Enumeration<URL> e = this.getNewTempClassLoader().getResources("META-INF/persistence.xml"); e.hasMoreElements(); ) { final URL url = e.nextElement(); final InputStream in = url.openStream(); final Document doc = documentBuilder.parse(in); in.close(); final NodeList persistenceUnits = doc.getElementsByTagNameNS(PERSISTENCE_NS, "persistence-unit"); for (int i = persistenceUnits.getLength() - 1; i >= 0; i--) { final Element persistenceUnit = (Element) persistenceUnits.item(i); final NodeList classes = persistenceUnit.getElementsByTagNameNS(PERSISTENCE_NS, "class"); for (int j = classes.getLength() - 1; j >= 0; j--) { final Element clazz = (Element) classes.item(j); this.managedClasses.add(clazz.getFirstChild().getNodeValue()); } } } } return this.managedClasses; } catch (final SAXException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final IOException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final ParserConfigurationException e) { getLogger().fatal(e); throw new RuntimeException(e); } } public boolean excludeUnlistedClasses() { return false; } public Properties getProperties() { return getEnvironment().getProperties(); } public ClassLoader getClassLoader() { if (this.classLoader == null) { this.classLoader = this.getClass().getClassLoader(); if (this.classLoader == null) { this.classLoader = ClassLoader.getSystemClassLoader(); } this.classLoader = new URLClassLoader(new URL[] { getEnvironment().getJpaRootUrl() }, this.classLoader); } return this.classLoader; } public void addTransformer(final ClassTransformer transformer) { if (this.transformers == null) { this.transformers = new LinkedList<ClassTransformer>(); } this.transformers.add(transformer); } public ClassLoader getNewTempClassLoader() { final List<URL> jarFileUrls = this.getJarFileUrls(); jarFileUrls.add(getEnvironment().getJpaRootUrl()); return new URLClassLoader(jarFileUrls.toArray(new URL[jarFileUrls.size()])); } }; } return this.persistenceUnitInfo; }
00
Code Sample 1: protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } } Code Sample 2: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { session = request.getSession(true); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { String searchTerm = new String(); if (request.getParameter("searchdb") != null) { searchTerm = request.getParameter("searchdb"); out.write("<ul>"); PreparedStatement sqlGetLikeBaseString = conn.prepareStatement("SELECT * FROM ENTRIES WHERE XTM_SESSION_ID = ? AND XTM_TEXT LIKE ?"); sqlGetLikeBaseString.setString(1, session.getId()); sqlGetLikeBaseString.setString(2, new String("%" + searchTerm + "%")); ResultSet res = sqlGetLikeBaseString.executeQuery(); while (res.next()) { out.write("<li>"); out.write(res.getString("XTM_TEXT")); out.write("</li>"); } out.write("</ul>"); res.close(); } if (request.getParameter("searchwiki") != null) { searchTerm = request.getParameter("searchwiki"); out.write("<ul>"); try { searchTerm = URLEncoder.encode(searchTerm, "UTF-8"); URL url = new URL("http://www.wikipedia.de/suggest.php?lang=de&search=" + searchTerm); URLConnection con = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line; while ((line = rd.readLine()) != null) { out.write("<li>"); String[] split = line.split("\t"); out.write(split[0]); out.write("</li>"); } rd.close(); } catch (Exception e) { e.printStackTrace(); } out.write("</ul>"); } else { return; } } catch (SQLException e) { out.println("Caught SQLException:" + e.getMessage()); } ; }
11
Code Sample 1: private static String hashToMD5(String sig) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(sig.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032X", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } } Code Sample 2: public String encryptToMD5(String info) { byte[] digesta = null; try { MessageDigest alga = MessageDigest.getInstance("MD5"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String rs = byte2hex(digesta); return rs; }
11
Code Sample 1: public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
11
Code Sample 1: private String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] data = md.digest(); return convertToHex(data); } catch (Exception ex) { ex.printStackTrace(); } return null; } Code Sample 2: public static String getDigest(String input) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(input.getBytes()); byte[] outDigest = md5.digest(); StringBuffer outBuf = new StringBuffer(33); for (int i = 0; i < outDigest.length; i++) { byte b = outDigest[i]; int hi = (b >> 4) & 0x0f; outBuf.append(MD5Digest.hexTab[hi]); int lo = b & 0x0f; outBuf.append(MD5Digest.hexTab[lo]); } return outBuf.toString(); }
00
Code Sample 1: public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); } Code Sample 2: public static CMLUnitList createUnitList(URL url) throws IOException, CMLException { Document dictDoc = null; InputStream in = null; try { in = url.openStream(); dictDoc = new CMLBuilder().build(in); } catch (NullPointerException e) { e.printStackTrace(); throw new CMLException("NULL " + e.getMessage() + S_SLASH + e.getCause() + " in " + url); } catch (ValidityException e) { throw new CMLException(S_EMPTY + e.getMessage() + S_SLASH + e.getCause() + " in " + url); } catch (ParsingException e) { e.printStackTrace(); throw new CMLException(e, " in " + url); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } CMLUnitList dt = null; if (dictDoc != null) { Element root = dictDoc.getRootElement(); if (root instanceof CMLUnitList) { dt = new CMLUnitList((CMLUnitList) root); } else { } } if (dt != null) { dt.indexEntries(); } return dt; }
11
Code Sample 1: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { URL url = new URL(upgradeURL); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); FileOutputStream out = new FileOutputStream(""); String bytes = ""; int data = buffIn.read(); int downloadedByteCount = 1; while (data != -1) { out.write(data); bytes.concat(Character.toString((char) data)); buffIn.read(); downloadedByteCount++; updateProgressBar(downloadedByteCount); } out.close(); buffIn.close(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(bytes.getBytes()); String hash = m.digest().toString(); if (hash.length() == 31) { hash = "0" + hash; } if (!hash.equalsIgnoreCase(md5Hash)) { } } catch (MalformedURLException e) { } catch (IOException io) { } catch (NoSuchAlgorithmException a) { } } Code Sample 2: public static String crypt(String senha) { String md5 = null; MessageDigest md; try { md = MessageDigest.getInstance(CRYPT_ALGORITHM); md.update(senha.getBytes()); Hex hex = new Hex(); md5 = new String(hex.encode(md.digest())); } catch (NoSuchAlgorithmException e) { logger.error(ResourceUtil.getLOGMessage("_nls.mensagem.geral.log.crypt.no.such.algorithm", CRYPT_ALGORITHM)); } return md5; }
11
Code Sample 1: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private void renameTo(File from, File to) { if (!from.exists()) return; if (to.exists()) to.delete(); boolean worked = false; try { worked = from.renameTo(to); } catch (Exception e) { database.logError(this, "" + e, null); } if (!worked) { database.logWarning(this, "Could not rename GEDCOM to " + to.getAbsolutePath(), null); try { to.delete(); final FileReader in = new FileReader(from); final FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); from.delete(); } catch (Exception e) { database.logError(this, "" + e, null); } } } Code Sample 2: public String getTags(String content) { StringBuffer xml = new StringBuffer(); OutputStreamWriter osw = null; BufferedReader br = null; try { String reqData = URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(content, "UTF-8"); URL service = new URL(cmdUrl); URLConnection urlConn = service.openConnection(); urlConn.setDoOutput(true); urlConn.connect(); osw = new OutputStreamWriter(urlConn.getOutputStream()); osw.write(reqData); osw.flush(); br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = null; while ((line = br.readLine()) != null) { xml.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (osw != null) { osw.close(); } if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } } return xml.toString(); }
11
Code Sample 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); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: @Override public void run() { try { jButton1.setEnabled(false); jButton2.setEnabled(false); URL url = new URL(updatePath + "currentVersion.txt"); URLConnection con = url.openConnection(); con.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; for (int i = 0; (line = in.readLine()) != null; i++) { URL fileUrl = new URL(updatePath + line); URLConnection filecon = fileUrl.openConnection(); InputStream stream = fileUrl.openStream(); int oneChar, count = 0; int size = filecon.getContentLength(); jProgressBar1.setMaximum(size); jProgressBar1.setValue(0); File testFile = new File(line); String build = ""; for (String dirtest : line.split("/")) { build += dirtest; if (!build.contains(".")) { File dirfile = new File(build); if (!dirfile.exists()) { dirfile.mkdir(); } } build += "/"; } if (testFile.length() == size) { } else { transferFile(line, fileUrl, size); if (line.endsWith("documents.zip")) { ZipInputStream in2 = new ZipInputStream(new FileInputStream(line)); ZipEntry entry; String pathDoc = line.split("documents.zip")[0]; File docDir = new File(pathDoc + "documents"); if (!docDir.exists()) { docDir.mkdir(); } while ((entry = in2.getNextEntry()) != null) { String outFilename = pathDoc + "documents/" + entry.getName(); OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } in2.close(); } if (line.endsWith("mysql.zip")) { ZipFile zipfile = new ZipFile(line); Enumeration entries = zipfile.entries(); String pathDoc = line.split("mysql.zip")[0]; File docDir = new File(pathDoc + "mysql"); if (!docDir.exists()) { docDir.mkdir(); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(pathDoc + "mysql/" + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); InputStream in2 = zipfile.getInputStream(entry); OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName())); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } in2.close(); out.close(); } } } jProgressBar2.setValue(i + 1); labelFileProgress.setText((i + 1) + "/" + numberFiles); } labelStatus.setText("Update Finished"); jButton1.setVisible(false); jButton2.setText("Finished"); jButton1.setEnabled(true); jButton2.setEnabled(true); } catch (IOException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: public void putDataFiles(String server, String username, String password, String folder, String destinationFolder) { try { FTPClient ftp = new FTPClient(); ftp.connect(server); System.out.println("Connected"); ftp.login(username, password); System.out.println("Logged in to " + server + "."); System.out.print(ftp.getReplyString()); ftp.changeWorkingDirectory(destinationFolder); System.out.println("Changed to directory " + destinationFolder); File localRoot = new File(folder); File[] files = localRoot.listFiles(); System.out.println("Number of files in dir: " + files.length); for (int i = 0; i < files.length; i++) { putFiles(ftp, files[i]); } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
00
Code Sample 1: protected void initializeGraphicalViewer() { getGraphicalViewer().setContents(loadModel()); getGraphicalViewer().addDropTargetListener(createTransferDropTargetListener()); getGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection().isEmpty()) { return; } loadProperties(((StructuredSelection) event.getSelection()).getFirstElement()); } }); } Code Sample 2: private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public synchronized int executeCommand(Vector<String> pvStatement) throws Exception { int ret = 0, i = 0; Statement stmt = null; String temp = ""; try { oConexion.setAutoCommit(false); stmt = oConexion.createStatement(); for (i = 0; i < pvStatement.size(); i++) { temp = (String) pvStatement.elementAt(i); ret += stmt.executeUpdate(temp); } oConexion.commit(); } catch (SQLException e) { oConexion.rollback(); throw e; } finally { stmt.close(); stmt = null; } return ret; } Code Sample 2: public static String upload(File tmpFile, URL url) throws IOException { StringBuffer reply = new StringBuffer(); URLConnection uc = url.openConnection(); ClientHttpRequest request = new ClientHttpRequest(uc); String file = "file"; String filename = tmpFile.getName(); InputStream fileinput = new FileInputStream(tmpFile); request.setParameter(file, filename, fileinput); InputStream serverInput = request.post(); BufferedReader in = new BufferedReader(new InputStreamReader(serverInput)); String line = in.readLine(); while (line != null) { reply.append(line + "\n"); line = in.readLine(); } in.close(); return reply.toString(); }
00
Code Sample 1: @Override public synchronized HttpURLConnection getTileUrlConnection(int zoom, int tilex, int tiley) throws IOException { HttpURLConnection conn = null; try { String url = getTileUrl(zoom, tilex, tiley); conn = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { throw e; } catch (Exception e) { log.error("", e); throw new IOException(e); } try { i.set("conn", conn); i.eval("addHeaders(conn);"); } catch (EvalError e) { String msg = e.getMessage(); if (!AH_ERROR.equals(msg)) { log.error(e.getClass() + ": " + e.getMessage(), e); throw new IOException(e); } } return conn; } Code Sample 2: public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; }
00
Code Sample 1: public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); } Code Sample 2: public static String encrypt(String algorithm, String str) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(str.getBytes()); StringBuffer sb = new StringBuffer(); byte[] bytes = md.digest(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception e) { return ""; } }
11
Code Sample 1: public UploadHubList(String server, String username, String password, String remoteFile, String filePath) throws SocketException, IOException { FTPClient ftp = new FTPClient(); System.out.println("\t."); ftp.connect(server); System.out.println("\t.."); ftp.login(username, password); System.out.print(ftp.getReplyString()); System.out.println("\t..."); ftp.storeFile(remoteFile, new FileInputStream(filePath)); System.out.print(ftp.getReplyString()); } Code Sample 2: public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 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()); } } Code Sample 2: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); }
11
Code Sample 1: public void testSavepoint4() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #savepoint4 (data int)"); stmt.close(); con.setAutoCommit(false); for (int i = 0; i < 3; i++) { System.out.println("iteration: " + i); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)"); pstmt.setInt(1, 1); assertTrue(pstmt.executeUpdate() == 1); Savepoint savepoint = con.setSavepoint(); assertNotNull(savepoint); assertTrue(savepoint.getSavepointId() == 1); try { savepoint.getSavepointName(); assertTrue(false); } catch (SQLException e) { } pstmt.setInt(1, 2); assertTrue(pstmt.executeUpdate() == 1); pstmt.close(); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(savepoint); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(); } con.setAutoCommit(true); } Code Sample 2: public void criarQuestaoDiscursiva(QuestaoDiscursiva q) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO discursiva (id_questao,gabarito) VALUES (?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setString(2, q.getGabarito()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
00
Code Sample 1: private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; } Code Sample 2: private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; }
00
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } } Code Sample 2: protected void writeToResponse(InputStream stream, HttpServletResponse response) throws IOException { OutputStream output = response.getOutputStream(); try { IOUtils.copy(stream, output); } finally { try { stream.close(); } finally { output.close(); } } }
00
Code Sample 1: private void createProject(IProgressMonitor monitor, boolean launchNewTestWizard) { try { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(namePage.getProjectName()); IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); if (!Platform.getLocation().equals(namePage.getLocationPath())) description.setLocation(namePage.getLocationPath()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); ICommand buildCommand = description.newCommand(); buildCommand.setBuilderName(JavaCore.BUILDER_ID); description.setBuildSpec(new ICommand[] { buildCommand }); project.create(description, monitor); project.open(monitor); IJavaProject javaProject = JavaCore.create(project); IFolder testFolder = project.getFolder("tests"); testFolder.create(false, true, monitor); IFolder srcFolder = project.getFolder("src"); srcFolder.create(false, true, monitor); IFolder binFolder = project.getFolder("bin"); binFolder.create(false, true, monitor); IFolder libFolder = project.getFolder("lib"); libFolder.create(false, true, monitor); try { FileUtils.copyFile(new Path(Platform.asLocalURL(CubicTestPlugin.getDefault().find(new Path("lib/CubicTestElementAPI.jar"))).getPath()).toFile(), libFolder.getFile("CubicTestElementAPI.jar").getLocation().toFile()); FileUtils.copyFile(new Path(Platform.asLocalURL(CubicTestPlugin.getDefault().find(new Path("lib/CubicUnit.jar"))).getPath()).toFile(), libFolder.getFile("CubicUnit.jar").getLocation().toFile()); } catch (IOException e1) { e1.printStackTrace(); } javaProject.setOutputLocation(binFolder.getFullPath(), monitor); IClasspathEntry[] classpath; classpath = new IClasspathEntry[] { JavaCore.newSourceEntry(srcFolder.getFullPath()), JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")), JavaCore.newLibraryEntry(libFolder.getFile("CubicTestElementAPI.jar").getFullPath(), null, null), JavaCore.newLibraryEntry(libFolder.getFile("CubicUnit.jar").getFullPath(), null, null) }; javaProject.setRawClasspath(classpath, binFolder.getFullPath(), monitor); ResourceNavigator navigator = null; IViewPart viewPart = workbench.getActiveWorkbenchWindow().getActivePage().getViewReferences()[0].getView(false); if (viewPart instanceof ResourceNavigator) { navigator = (ResourceNavigator) viewPart; } if (launchNewTestWizard) { launchNewTestWizard(testFolder); if (navigator != null && testFolder.members().length > 0) { navigator.selectReveal(new StructuredSelection(testFolder.members()[0])); } } project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { e.printStackTrace(); } } Code Sample 2: protected void copy(URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { in = url.openStream(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); }
00
Code Sample 1: private Face(String font) throws IOException { characterWidths = new double[256]; StringBuffer sb = new StringBuffer(); sb.append('/'); sb.append(Constants.FONTS_DIR); sb.append('/'); sb.append(font); sb.append(Constants.CHAR_WIDTHS_SUFFIX); String path = sb.toString(); URL url = getClass().getResource(path); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); int pos = 0; String width = br.readLine(); while (width != null && pos < 256) { characterWidths[pos] = Double.parseDouble(width); pos++; width = br.readLine(); } } Code Sample 2: void readData() { String[] nextLine; int line; double value; URL url = null; String FileToRead; try { for (int i = 0; i < names.length; i++) { FileToRead = "data/" + names[i] + ".csv"; url = new URL(ja.getCodeBase(), FileToRead); System.out.println(url.toString()); InputStream in = url.openStream(); CSVReader reader = new CSVReader(new InputStreamReader(in)); line = 0; while ((nextLine = reader.readNext()) != null) { allset.months[line] = Integer.parseInt(nextLine[0].substring(0, 2)); allset.years[line] = Integer.parseInt(nextLine[0].substring(6, 10)); value = Double.parseDouble(nextLine[1]); allset.values.getDataRef()[line][i] = value; line++; } } } catch (IOException e) { System.err.println("File Read Exception"); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: @Test public void testWriteAndReadFirstLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile file = new RFile(directory1, "testreadwrite1st.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
11
Code Sample 1: public static String md5(String text) { String encrypted = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); encrypted = hex(md.digest()); } catch (NoSuchAlgorithmException nsaEx) { } return encrypted; } Code Sample 2: public static String digest(String password) { try { byte[] digest; synchronized (__md5Lock) { if (__md == null) { try { __md = MessageDigest.getInstance("MD5"); } catch (Exception e) { Log.warn(e); return null; } } __md.reset(); __md.update(password.getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) { Log.warn(e); return null; } }
11
Code Sample 1: 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; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } Code Sample 2: private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; }
11
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } }
11
Code Sample 1: public String getData() throws ValueFormatException, RepositoryException, IOException { InputStream is = getStream(); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); IOUtils.closeQuietly(is); return sw.toString(); } Code Sample 2: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public void run() { long id = 0; try { URL url = new URL(httpRequest + blockSize); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); try { String str = in.readLine(); if (str == null) { throw new IllegalStateException("Parsing error"); } if (str.matches(".*SUCCESS.*")) { str = in.readLine(); if (str.matches(".*Start:.*")) { str = in.readLine(); id = Long.parseLong(str); } else { throw new IllegalStateException("Invalid response for blocksize(" + blockSize + "):" + str); } } else { throw new IllegalStateException("Invalid response for blocksize(" + blockSize + "):" + str); } } finally { in.close(); } if (id <= 0) throw new IllegalStateException("Invalid GUID start value " + id); synchronized (ids) { boolean absent = ids.add(new Long(id)); if (!absent) { logErrorMessage(id + " already exists for thread " + Thread.currentThread().getName()); } } } catch (Exception e) { logErrorMessage("Unexpected IdGenerator thread failure" + e.getMessage()); e.printStackTrace(); } finally { synchronized (test) { test.liveThreads--; test.notify(); } } } Code Sample 2: @Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } return status > 199 && status < 400; }