label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static Node carregaModeloJME(String caminho) { try { URL urlModelo = ModelUtils.class.getClassLoader().getResource(caminho); BufferedInputStream leitorBinario = new BufferedInputStream(urlModelo.openStream()); Node modelo = (Node) BinaryImporter.getInstance().load(leitorBinario); modelo.setModelBound(new BoundingBox()); modelo.updateModelBound(); return modelo; } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public void delete(String user) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from Principals where PrincipalId = '" + user + "'"); stmt.executeUpdate("delete from Roles where PrincipalId = '" + user + "'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
11
Code Sample 1: protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } } Code Sample 2: public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
00
Code Sample 1: public static void loginBayFiles() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to bayfiles.com"); HttpPost httppost = new HttpPost("http://bayfiles.com/ajax_login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("username", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("SESSID")) { sessioncookie = "SESSID=" + escookie.getValue(); System.out.println(sessioncookie); login = true; System.out.println("BayFiles.com Login success :)"); } } if (!login) { System.out.println("BayFiles.com Login failed :("); } } Code Sample 2: public static String digest(String text, String algorithm, String charsetName) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes(charsetName), 0, text.length()); return convertToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("unexpected exception: " + e, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception: " + e, e); } }
11
Code Sample 1: private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) { MessageDigest md; byte[] temp_digest, pass_digest; byte[] hex_digest = new byte[35]; byte[] scrambled = scrambledPassword.getBytes(); try { md = MessageDigest.getInstance("MD5"); md.update(plainPassword.getBytes("US-ASCII")); md.update(user.getBytes("US-ASCII")); temp_digest = md.digest(); Utils.bytesToHex(temp_digest, hex_digest, 0); md.update(hex_digest, 0, 32); md.update(salt.getBytes()); pass_digest = md.digest(); Utils.bytesToHex(pass_digest, hex_digest, 3); hex_digest[0] = (byte) 'm'; hex_digest[1] = (byte) 'd'; hex_digest[2] = (byte) '5'; for (int i = 0; i < hex_digest.length; i++) { if (scrambled[i] != hex_digest[i]) { return false; } } } catch (Exception e) { logger.error(e); } return true; } Code Sample 2: public static final String hash(String data) { MessageDigest digest = null; if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. " + "Jive will be unable to function normally."); nsae.printStackTrace(); } } digest.update(data.getBytes()); return encodeHex(digest.digest()); }
00
Code Sample 1: private static String readJarURL(URL url) throws IOException { JarURLConnection juc = (JarURLConnection) url.openConnection(); InputStream in = juc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { out.write(i); i = in.read(); } return out.toString(); } Code Sample 2: @Override protected Map<String, Definition> loadDefinitionsFromURL(URL url) { Map<String, Definition> defsMap = null; try { URLConnection connection = url.openConnection(); connection.connect(); lastModifiedDates.put(url.toExternalForm(), connection.getLastModified()); defsMap = reader.read(connection.getInputStream()); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("File " + null + " not found, continue [" + e.getMessage() + "]"); } } return defsMap; }
00
Code Sample 1: private final int copyFiles(File[] list, String dest, boolean dest_is_full_name) throws InterruptedException { Context c = ctx; File file = null; for (int i = 0; i < list.length; i++) { boolean existed = false; FileChannel in = null; FileChannel out = null; File outFile = null; file = list[i]; if (file == null) { error(c.getString(R.string.unkn_err)); break; } String uri = file.getAbsolutePath(); try { if (isStopReq()) { error(c.getString(R.string.canceled)); break; } long last_modified = file.lastModified(); String fn = file.getName(); outFile = dest_is_full_name ? new File(dest) : new File(dest, fn); if (file.isDirectory()) { if (depth++ > 40) { error(ctx.getString(R.string.too_deep_hierarchy)); break; } else if (outFile.exists() || outFile.mkdir()) { copyFiles(file.listFiles(), outFile.getAbsolutePath(), false); if (errMsg != null) break; } else error(c.getString(R.string.cant_md, outFile.getAbsolutePath())); depth--; } else { if (existed = outFile.exists()) { int res = askOnFileExist(c.getString(R.string.file_exist, outFile.getAbsolutePath()), commander); if (res == Commander.SKIP) continue; if (res == Commander.REPLACE) { if (outFile.equals(file)) continue; else outFile.delete(); } if (res == Commander.ABORT) break; } if (move) { long len = file.length(); if (file.renameTo(outFile)) { counter++; totalBytes += len; int so_far = (int) (totalBytes * conv); sendProgress(outFile.getName() + " " + c.getString(R.string.moved), so_far, 0); continue; } } in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outFile).getChannel(); long size = in.size(); final long max_chunk = 524288; long pos = 0; long chunk = size > max_chunk ? max_chunk : size; long t_chunk = 0; long start_time = 0; int speed = 0; int so_far = (int) (totalBytes * conv); String sz_s = Utils.getHumanSize(size); String rep_s = c.getString(R.string.copying, fn); for (pos = 0; pos < size; ) { if (t_chunk == 0) start_time = System.currentTimeMillis(); sendProgress(rep_s + sizeOfsize(pos, sz_s), so_far, (int) (totalBytes * conv), speed); long transferred = in.transferTo(pos, chunk, out); pos += transferred; t_chunk += transferred; totalBytes += transferred; if (isStopReq()) { Log.d(TAG, "Interrupted!"); error(c.getString(R.string.canceled)); return counter; } long time_delta = System.currentTimeMillis() - start_time; if (time_delta > 0) { speed = (int) (1000 * t_chunk / time_delta); t_chunk = 0; } } in.close(); out.close(); in = null; out = null; if (i >= list.length - 1) sendProgress(c.getString(R.string.copied_f, fn) + sizeOfsize(pos, sz_s), (int) (totalBytes * conv)); counter++; } if (move) file.delete(); outFile.setLastModified(last_modified); final int GINGERBREAD = 9; if (android.os.Build.VERSION.SDK_INT >= GINGERBREAD) ForwardCompat.setFullPermissions(outFile); } catch (SecurityException e) { error(c.getString(R.string.sec_err, e.getMessage())); } catch (FileNotFoundException e) { error(c.getString(R.string.not_accs, e.getMessage())); } catch (ClosedByInterruptException e) { error(c.getString(R.string.canceled)); } catch (IOException e) { String msg = e.getMessage(); error(c.getString(R.string.acc_err, uri, msg != null ? msg : "")); } catch (RuntimeException e) { error(c.getString(R.string.rtexcept, uri, e.getMessage())); } finally { try { if (in != null) in.close(); if (out != null) out.close(); if (!move && errMsg != null && outFile != null && !existed) { Log.i(TAG, "Deleting failed output file"); outFile.delete(); } } catch (IOException e) { error(c.getString(R.string.acc_err, uri, e.getMessage())); } } } return counter; } Code Sample 2: public static String getMD5(final String data) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(data.getBytes()); BigInteger bigInt = new BigInteger(1, m.digest()); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return e.getMessage(); } }
00
Code Sample 1: public static boolean insereLicao(final Connection con, Licao lic, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodLicao(con, lic); String titulo = lic.getTitulo().replaceAll("['\"]", ""); String coment = lic.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO licao VALUES(" + lic.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO lic_aut VALUES(" + lic.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "LICAO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } } Code Sample 2: 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.close(output); } } finally { IOUtils.close(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 void testSimpleHttpPostsWithContentLength() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } Code Sample 2: public void run() { try { File outDir = new File(outDirTextField.getText()); if (!outDir.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen directory does not exist!", "Directory Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.isDirectory()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen file is not a directory!", "Not a Directory Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.canWrite()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Cannot write to the chosen directory!", "Directory Not Writeable Error", JOptionPane.ERROR_MESSAGE); } }); return; } File archiveDir = new File("foo.bar").getAbsoluteFile().getParentFile(); URL baseUrl = UnpackWizard.class.getClassLoader().getResource(UnpackWizard.class.getName().replaceAll("\\.", "/") + ".class"); if (baseUrl.getProtocol().equals("jar")) { String jarPath = baseUrl.getPath(); jarPath = jarPath.substring(0, jarPath.indexOf('!')); if (jarPath.startsWith("file:")) { try { archiveDir = new File(new URI(jarPath)).getAbsoluteFile().getParentFile(); } catch (URISyntaxException e1) { e1.printStackTrace(System.err); } } } SortedMap<Integer, String> inputFileNames = new TreeMap<Integer, String>(); for (Entry<Object, Object> anEntry : indexProperties.entrySet()) { String key = anEntry.getKey().toString(); if (key.startsWith("archive file ")) { inputFileNames.put(Integer.parseInt(key.substring("archive file ".length())), anEntry.getValue().toString()); } } byte[] buff = new byte[64 * 1024]; try { long bytesToWrite = 0; long bytesReported = 0; long bytesWritten = 0; for (String aFileName : inputFileNames.values()) { File aFile = new File(archiveDir, aFileName); if (aFile.exists()) { if (aFile.isFile()) { bytesToWrite += aFile.length(); } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" is not a standard file!", "Non Standard File Error", JOptionPane.ERROR_MESSAGE); } }); return; } } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" does not exist!", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } } MultiFileInputStream mfis = new MultiFileInputStream(archiveDir, inputFileNames.values().toArray(new String[inputFileNames.size()])); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(mfis)); TarArchiveEntry tarEntry = tis.getNextTarEntry(); while (tarEntry != null) { File outFile = new File(outDir.getAbsolutePath() + "/" + tarEntry.getName()); if (outFile.exists()) { final File wrongFile = outFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Was about to write out file \"" + wrongFile.getAbsolutePath() + "\" but it already " + "exists.\nPlease [re]move existing files out of the way " + "and try again.", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (tarEntry.isDirectory()) { outFile.getAbsoluteFile().mkdirs(); } else { outFile.getAbsoluteFile().getParentFile().mkdirs(); OutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); int len = tis.read(buff, 0, buff.length); while (len != -1) { os.write(buff, 0, len); bytesWritten += len; if (bytesWritten - bytesReported > (10 * 1024 * 1024)) { bytesReported = bytesWritten; final int progress = (int) (bytesReported * 100 / bytesToWrite); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(progress); } }); } len = tis.read(buff, 0, buff.length); } os.close(); } tarEntry = tis.getNextTarEntry(); } long expectedCrc = 0; try { expectedCrc = Long.parseLong(indexProperties.getProperty("CRC32", "0")); } catch (NumberFormatException e) { System.err.println("Error while obtaining the expected CRC"); e.printStackTrace(System.err); } if (mfis.getCRC() == expectedCrc) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Extraction completed successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE); } }); return; } else { System.err.println("CRC Error: was expecting " + expectedCrc + " but got " + mfis.getCRC()); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "CRC Error: the data extracted does not have the expected CRC!\n" + "You should probably delete the extracted files, as they are " + "likely to be invalid.", "CRC Error", JOptionPane.ERROR_MESSAGE); } }); return; } } catch (final IOException e) { e.printStackTrace(System.err); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Input/Output Error: " + e.getLocalizedMessage(), "Input/Output Error", JOptionPane.ERROR_MESSAGE); } }); return; } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); setEnabled(true); } }); } }
11
Code Sample 1: public static void copyToFileAndCloseStreams(InputStream istr, File destFile) throws IOException { OutputStream ostr = null; try { ostr = new FileOutputStream(destFile); IOUtils.copy(istr, ostr); } finally { if (ostr != null) ostr.close(); if (istr != null) istr.close(); } } Code Sample 2: public static void copyFile(IPath fromFileName, IPath toFileName) throws IOException { File fromFile = fromFileName.toFile(); File toFile = toFileName.toFile(); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } InputStream from = null; OutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(fromFile)); to = new BufferedOutputStream(new FileOutputStream(toFile)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
11
Code Sample 1: private void handleUpload(CommonsMultipartFile file, String newFileName, String uploadDir) throws IOException, FileNotFoundException { File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } InputStream stream = file.getInputStream(); OutputStream bos = new FileOutputStream(uploadDir + newFileName); IOUtils.copy(stream, bos); } 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 connect(final URLConnectAdapter urlAdapter) { if (this.connectSettings == null) { throw new IllegalStateException("Invalid Connect Settings (is null)"); } final HttpURLConnection httpConnection = (HttpURLConnection) urlAdapter.openConnection(); BufferedReader in; try { in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); final StringBuilder buf = new StringBuilder(200); String str; while ((str = in.readLine()) != null) { buf.append(str); buf.append('\n'); } final ConnectResult result = new ConnectResult(httpConnection.getResponseCode(), buf.toString()); final Map<String, List<String>> headerFields = httpConnection.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) { final String key = entry.getKey(); final List<String> val = entry.getValue(); if ((val != null) && (val.size() > 1)) { System.out.println("WARN: Invalid header value : " + key + " url=" + this.connectSettings.getUrl()); } if (key != null) { result.addHeader(key, val.get(0), val); } else { result.addHeader("Status", val.get(0), val); } } this.lastResult = result; } catch (IOException e) { throw new ConnectException(e); } } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version_" + datastream + ".xml\""); } String xmlContent = URLDecoder.decode(req.getParameterValues(Constants.PARAM_CONTENT)[0], "UTF-8"); InputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8")); ServletOutputStream os = resp.getOutputStream(); IOUtils.copyStreams(is, os); os.flush(); } Code Sample 2: public static URL getAuthenticationURL(String apiKey, String permission, String sharedSecret) throws Exception { String apiSig = sharedSecret + "api_key" + apiKey + "perms" + permission; MessageDigest m = MessageDigest.getInstance("MD5"); m.update(apiSig.getBytes(), 0, apiSig.length()); apiSig = new BigInteger(1, m.digest()).toString(16); StringBuffer buffer = new StringBuffer(); buffer.append("http://flickr.com/services/auth/?"); buffer.append("api_key=" + apiKey); buffer.append("&").append("perms=").append(permission); buffer.append("&").append("api_sig=").append(apiSig); return new URL(buffer.toString()); }
00
Code Sample 1: protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); } Code Sample 2: public static byte[] getURLContent(String urlPath) { HttpURLConnection conn = null; InputStream inStream = null; byte[] buffer = null; try { URL url = new URL(urlPath); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setUseCaches(false); conn.setDefaultUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(60000); conn.connect(); int repCode = conn.getResponseCode(); if (repCode == 200) { inStream = conn.getInputStream(); int contentLength = conn.getContentLength(); buffer = getResponseBody(inStream, contentLength); } } catch (Exception ex) { logger.error("", ex); } finally { try { if (inStream != null) { inStream.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception ex) { } } return buffer; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void download(RequestContext ctx) throws IOException { if (ctx.isRobot()) { ctx.forbidden(); return; } long id = ctx.id(); File bean = File.INSTANCE.Get(id); if (bean == null) { ctx.not_found(); return; } String f_ident = ctx.param("fn", ""); if (id >= 100 && !StringUtils.equals(f_ident, bean.getIdent())) { ctx.not_found(); return; } if (bean.IsLoginRequired() && ctx.user() == null) { StringBuilder login = new StringBuilder(LinkTool.home("home/login?goto_page=")); ctx.redirect(login.toString()); return; } FileInputStream fis = null; try { java.io.File file = StorageService.FILES.readFile(bean.getPath()); fis = new FileInputStream(file); ctx.response().setContentLength((int) file.length()); String ext = FilenameUtils.getExtension(bean.getPath()); String mine_type = Multimedia.mime_types.get(ext); if (mine_type != null) ctx.response().setContentType(mine_type); String ua = ctx.header("user-agent"); if (ua != null && ua.indexOf("Firefox") >= 0) ctx.header("Content-Disposition", "attachment; filename*=\"utf8''" + LinkTool.encode_url(bean.getName()) + "." + ext + "\""); else ctx.header("Content-Disposition", "attachment; filename=" + LinkTool.encode_url(bean.getName() + "." + ext)); IOUtils.copy(fis, ctx.response().getOutputStream()); bean.IncDownloadCount(1); } finally { IOUtils.closeQuietly(fis); } }
00
Code Sample 1: public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; } Code Sample 2: private void mergeOne(String level, char strand, String filename, Path outPath, FileSystem srcFS, FileSystem dstFS, Timer to) throws IOException { to.start(); final OutputStream outs = dstFS.create(new Path(outPath, filename)); final FileStatus[] parts = srcFS.globStatus(new Path(sorted ? getSortOutputDir(level, strand) : wrkDir, filename + "-[0-9][0-9][0-9][0-9][0-9][0-9]")); for (final FileStatus part : parts) { final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, getConf(), false); ins.close(); } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarize :: Merged %s%c in %d.%03d s.\n", level, strand, to.stopS(), to.fms()); }
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 _saveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String subcmd) throws WebAssetException, Exception { long maxsize = 50; long maxwidth = 3000; long maxheight = 3000; long minheight = 10; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); try { UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req); String parent = ParamUtil.getString(req, "parent"); int countFiles = ParamUtil.getInteger(req, "countFiles"); int fileCounter = 0; Folder folder = (Folder) InodeFactory.getInode(parent, Folder.class); _checkUserPermissions(folder, user, PERMISSION_WRITE); String userId = user.getUserId(); String customMessage = "Some file does not match the filters specified by the folder: "; boolean filterError = false; for (int k = 0; k < countFiles; k++) { File file = new File(); String title = ParamUtil.getString(req, "title" + k); String friendlyName = ParamUtil.getString(req, "friendlyName" + k); Date publishDate = new Date(); String fileName = ParamUtil.getString(req, "fileName" + k); fileName = checkMACFileName(fileName); if (!FolderFactory.matchFilter(folder, fileName)) { customMessage += fileName + ", "; filterError = true; continue; } if (fileName.length() > 0) { String mimeType = FileFactory.getMimeType(fileName); String URI = folder.getPath() + fileName; String suffix = UtilMethods.getFileExtension(fileName); file.setTitle(title); file.setFileName(fileName); file.setFriendlyName(friendlyName); file.setPublishDate(publishDate); file.setModUser(userId); InodeFactory.saveInode(file); String filePath = FileFactory.getRealAssetsRootPath(); new java.io.File(filePath).mkdir(); java.io.File uploadedFile = uploadReq.getFile("uploadedFile" + k); Logger.debug(this, "bytes" + uploadedFile.length()); file.setSize((int) uploadedFile.length() - 2); file.setMimeType(mimeType); Host host = HostFactory.getCurrentHost(httpReq); Identifier ident = IdentifierFactory.getIdentifierByURI(URI, host); String message = ""; if ((FileFactory.existsFileName(folder, fileName))) { InodeFactory.deleteInode(file); message = "The uploaded file " + fileName + " already exists in this folder"; SessionMessages.add(req, "custommessage", message); } else { String fileInodePath = String.valueOf(file.getInode()); if (fileInodePath.length() == 1) { fileInodePath = fileInodePath + "0"; } fileInodePath = fileInodePath.substring(0, 1) + java.io.File.separator + fileInodePath.substring(1, 2); new java.io.File(filePath + java.io.File.separator + fileInodePath.substring(0, 1)).mkdir(); new java.io.File(filePath + java.io.File.separator + fileInodePath).mkdir(); java.io.File f = new java.io.File(filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); java.io.FileOutputStream fout = new java.io.FileOutputStream(f); FileChannel outputChannel = fout.getChannel(); FileChannel inputChannel = new java.io.FileInputStream(uploadedFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); outputChannel.force(false); outputChannel.close(); inputChannel.close(); Logger.debug(this, "SaveFileAction New File in =" + filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); if (suffix.equals("jpg") || suffix.equals("gif")) { com.dotmarketing.util.Thumbnail.resizeImage(filePath + java.io.File.separator + fileInodePath + java.io.File.separator, String.valueOf(file.getInode()), suffix); int height = javax.imageio.ImageIO.read(f).getHeight(); file.setHeight(height); Logger.debug(this, "File height=" + height); int width = javax.imageio.ImageIO.read(f).getWidth(); file.setWidth(width); Logger.debug(this, "File width=" + width); long size = (f.length() / 1024); WebAssetFactory.createAsset(file, userId, folder); } else { WebAssetFactory.createAsset(file, userId, folder); } WorkingCache.addToWorkingAssetToCache(file); _setFilePermissions(folder, file, user); fileCounter += 1; if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH)) { try { PublishFactory.publishAsset(file, httpReq); if (fileCounter > 1) { SessionMessages.add(req, "message", "message.file_asset.save"); } else { SessionMessages.add(req, "message", "message.fileupload.save"); } } catch (WebAssetException wax) { Logger.error(this, wax.getMessage(), wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } } } } } if (filterError) { customMessage = customMessage.substring(0, customMessage.lastIndexOf(",")); SessionMessages.add(req, "custommessage", customMessage); } } catch (IOException e) { Logger.error(this, "Exception saving file: " + e.getMessage()); throw new ActionException(e.getMessage()); } }
00
Code Sample 1: public static URL getComponentXmlFileWith(String name) throws Exception { List<URL> all = getComponentXmlFiles(); for (URL url : all) { InputStream stream = null; try { stream = url.openStream(); Element root = XML.getRootElement(stream); for (Element elem : (List<Element>) root.elements()) { String ns = elem.getNamespace().getURI(); if (name.equals(elem.attributeValue("name"))) { return url; } } } finally { Resources.closeStream(stream); } } return null; } Code Sample 2: private LSInput resolveResource(String aPublicId, String aSystemId, String aBaseURI, boolean baseUsed) { LSInput lsInput = new DefaultLSInput(); lsInput.setPublicId(aPublicId); lsInput.setSystemId(aSystemId); String base = null; try { int baseEndPos = -1; if (aBaseURI != null) { baseEndPos = aBaseURI.lastIndexOf("/"); } if (baseEndPos <= 0) { if (baseUsed) { return null; } else { return resolveResource(aPublicId, aSystemId, schemaBasePath + "/" + aSystemId, true); } } base = aBaseURI.substring(0, baseEndPos); URL url = new URL(base + "/" + aSystemId); lsInput.setByteStream(url.openConnection().getInputStream()); return lsInput; } catch (IOException e) { return resolveResource(aPublicId, aSystemId, base, baseUsed); } }
11
Code Sample 1: public void jsFunction_addFile(ScriptableFile infile) throws IOException { if (!infile.jsFunction_exists()) throw new IllegalArgumentException("Cannot add a file that doesn't exists to an archive"); ZipArchiveEntry entry = new ZipArchiveEntry(infile.getName()); entry.setSize(infile.jsFunction_getSize()); out.putArchiveEntry(entry); try { InputStream inStream = infile.jsFunction_createInputStream(); IOUtils.copy(inStream, out); inStream.close(); } finally { out.closeArchiveEntry(); } } Code Sample 2: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; }
11
Code Sample 1: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } Code Sample 2: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
00
Code Sample 1: private static Image tryLoadImageFromFile(String filename, String path, int width, int height) { Image image = null; try { URL url; url = new URL("file:" + path + pathSeparator + fixFilename(filename)); if (url.openStream() != null) { image = Toolkit.getDefaultToolkit().getImage(url); } } catch (MalformedURLException e) { } catch (IOException e) { } if (image != null) { return image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH); } else { 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 void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public String getPloidy(String source) { StringBuilder ploidyHtml = new StringBuilder(); String hyperdiploidyUrl = customParameters.getHyperdiploidyUrl(); String urlString = hyperdiploidyUrl + "?source=" + source; URL url = null; try { url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; while ((line = in.readLine()) != null) { ploidyHtml.append(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ploidyHtml.toString(); }
11
Code Sample 1: public static String md5(String value) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); try { messageDigest.update(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { messageDigest.update(value.getBytes()); } byte[] bytes = messageDigest.digest(); return byteArrayToHexString(bytes); } Code Sample 2: @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnClear) { passwordField.setText(""); } for (int i = 0; i < 10; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; sql = "select password from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } setVisible(false); setTries(0); Error.log(4003, "Senha de uso �nico verificada positivamente."); Error.log(4002, "Autentica��o etapa 3 encerrada."); ManagerWindow mw = new ManagerWindow(login); mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); int tries = getTries(); if (tries == 0) { Error.log(4004, "Primeiro erro da senha de uso �nico contabilizado."); } else if (tries == 1) { Error.log(4005, "Segundo erro da senha de uso �nico contabilizado."); } else if (tries == 2) { Error.log(4006, "Terceiro erro da senha de uso �nico contabilizado."); Error.log(4007, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 3."); Error.log(4002, "Autentica��o etapa 3 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } }
11
Code Sample 1: private void copyFile(String sourceFilename, String destDirname) throws BuildException { log("Copying file " + sourceFilename + " to " + destDirname); File destFile = getDestFile(sourceFilename, destDirname); InputStream inStream = null; OutputStream outStream = null; try { inStream = new BufferedInputStream(new FileInputStream(sourceFilename)); outStream = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] buffer = new byte[1024]; int n = 0; while ((n = inStream.read(buffer)) != -1) outStream.write(buffer, 0, n); } catch (Exception e) { throw new BuildException("Failed to copy file \"" + sourceFilename + "\" to directory \"" + destDirname + "\""); } finally { try { if (inStream != null) inStream.close(); } catch (IOException e) { } try { if (outStream != null) outStream.close(); } catch (IOException 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(); }
00
Code Sample 1: public boolean saveVideoXMLOnWebserver(String text) { boolean error = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.getWebserver().getUrl()); System.out.println("Connected to " + this.getWebserver().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } if (!ftp.login(this.getWebserver().getFtpBenutzer(), this.getWebserver().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String tmpSeminarID = this.getSeminarID(); if (tmpSeminarID == null) tmpSeminarID = "unbekannt"; try { ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); } catch (Exception e) { ftp.makeDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ByteArrayInputStream videoIn = new ByteArrayInputStream(text.getBytes()); ftp.enterLocalPassiveMode(); ftp.storeFile("video.xml", videoIn); videoIn.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei video.xml konnte nicht auf Webserver kopiert werden."); error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return error; } Code Sample 2: private void getRandomGUID(boolean secure) throws NoSuchAlgorithmException { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); throw 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); } }
00
Code Sample 1: public ProcessorOutput createOutput(String name) { ProcessorOutput output = new ProcessorImpl.CacheableTransformerOutputImpl(getClass(), name) { protected void readImpl(org.orbeon.oxf.pipeline.api.PipelineContext context, final ContentHandler contentHandler) { ProcessorInput i = getInputByName(INPUT_DATA); try { Grammar grammar = (Grammar) readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader() { public Object read(org.orbeon.oxf.pipeline.api.PipelineContext context, ProcessorInput input) { final Locator[] locator = new Locator[1]; GrammarReader grammarReader = new XMLSchemaReader(new GrammarReaderController() { public void error(Locator[] locators, String s, Exception e) { throw new ValidationException(s, e, new LocationData(locators[0])); } public void warning(Locator[] locators, String s) { throw new ValidationException(s, new LocationData(locators[0])); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = URLFactory.createURL((locator[0] != null && locator[0].getSystemId() != null) ? locator[0].getSystemId() : null, systemId); InputSource i = new InputSource(url.openStream()); i.setSystemId(url.toString()); return i; } }); readInputAsSAX(context, input, new ForwardingContentHandler(grammarReader) { public void setDocumentLocator(Locator loc) { super.setDocumentLocator(loc); locator[0] = loc; } }); return grammarReader.getResultAsGrammar(); } }); DocumentDeclaration vgm = new REDocumentDeclaration(grammar.getTopLevel(), new ExpressionPool()); Verifier verifier = new Verifier(vgm, new ErrorHandler()) { boolean stopDecorating = false; private void generateErrorElement(ValidationException ve) throws SAXException { if (decorateOutput && ve != null) { if (!stopDecorating) { AttributesImpl a = new AttributesImpl(); a.addAttribute("", ValidationProcessor.MESSAGE_ATTRIBUTE, ValidationProcessor.MESSAGE_ATTRIBUTE, "CDATA", ve.getSimpleMessage()); a.addAttribute("", ValidationProcessor.SYSTEMID_ATTRIBUTE, ValidationProcessor.SYSTEMID_ATTRIBUTE, "CDATA", ve.getLocationData().getSystemID()); a.addAttribute("", ValidationProcessor.LINE_ATTRIBUTE, ValidationProcessor.LINE_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getLine())); a.addAttribute("", ValidationProcessor.COLUMN_ATTRIBUTE, ValidationProcessor.COLUMN_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getCol())); contentHandler.startElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT, a); contentHandler.endElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT); stopDecorating = true; } } else { throw ve; } } public void characters(char[] chars, int i, int i1) throws SAXException { try { super.characters(chars, i, i1); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.characters(chars, i, i1); } public void endDocument() throws SAXException { try { super.endDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endDocument(); } public void endElement(String s, String s1, String s2) throws SAXException { try { super.endElement(s, s1, s2); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endElement(s, s1, s2); } public void startDocument() throws SAXException { try { super.startDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startDocument(); } public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException { ((ErrorHandler) getErrorHandler()).setElement(s, s1); try { super.startElement(s, s1, s2, attributes); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startElement(s, s1, s2, attributes); } public void endPrefixMapping(String s) { try { super.endPrefixMapping(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.endPrefixMapping(s); } catch (SAXException se) { throw new OXFException(se.getException()); } } public void processingInstruction(String s, String s1) { try { super.processingInstruction(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.processingInstruction(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void setDocumentLocator(Locator locator) { try { super.setDocumentLocator(locator); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } contentHandler.setDocumentLocator(locator); } public void skippedEntity(String s) { try { super.skippedEntity(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getMessage()); } } try { contentHandler.skippedEntity(s); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void startPrefixMapping(String s, String s1) { try { super.startPrefixMapping(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.startPrefixMapping(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } }; readInputAsSAX(context, getInputByName(INPUT_DATA), verifier); } catch (Exception e) { throw new OXFException(e); } } }; addOutput(name, output); return output; } Code Sample 2: @Test public void testCarResource() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); System.out.println("**** CarResource Via @MatrixParam ***"); HttpGet get = new HttpGet("http://localhost:9095/cars/matrix/mercedes/e55;color=black/2006"); HttpResponse response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println("**** CarResource Via PathSegment ***"); get = new HttpGet("http://localhost:9095/cars/segment/mercedes/e55;color=black/2006"); response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println("**** CarResource Via PathSegments ***"); get = new HttpGet("http://localhost:9095/cars/segments/mercedes/e55/amg/year/2006"); response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println("**** CarResource Via PathSegment ***"); get = new HttpGet("http://localhost:9095/cars/uriinfo/mercedes/e55;color=black/2006"); response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println(); System.out.println(); }
00
Code Sample 1: private static void copyFile(File sourceFile, File targetFile) throws FileSaveException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileSaveException(exceptionMessage, ioException); } } Code Sample 2: public static byte[] md5raw(String data) { try { MessageDigest md = MessageDigest.getInstance(MD); md.update(data.getBytes(UTF8)); return md.digest(); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } } Code Sample 2: public void run() { try { textUpdater.start(); int cnt; byte[] buf = new byte[4096]; File file = null; ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(filename))); ZipEntry ze = zis.getNextEntry(); FileOutputStream fos; while (ze != null) { if (ze.isDirectory()) { file = new File(ze.getName()); if (!file.exists()) { textUpdater.appendText("Creating directory: " + ze.getName() + "\n"); file.mkdirs(); } } else { textUpdater.appendText("Extracting file: " + ze.getName() + "\n"); fos = new FileOutputStream(dstdir + File.separator + ze.getName()); while ((cnt = zis.read(buf, 0, buf.length)) != -1) fos.write(buf, 0, cnt); fos.close(); } zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); if (complete != null) textUpdater.appendText(complete + "\n"); } catch (Exception e) { e.printStackTrace(); } textUpdater.setFinished(true); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static void zipFolder(File folder, ZipOutputStream zipOutputStream, String relativePath) throws IOException { File[] children = folder.listFiles(); for (int i = 0; i < children.length; i++) { File child = children[i]; if (child.isFile()) { String zipEntryName = children[i].getCanonicalPath().replace(relativePath + File.separator, ""); ZipEntry entry = new ZipEntry(zipEntryName); zipOutputStream.putNextEntry(entry); InputStream inputStream = new FileInputStream(child); IOUtils.copy(inputStream, zipOutputStream); inputStream.close(); } else { ZipUtil.zipFolder(child, zipOutputStream, relativePath); } } }
00
Code Sample 1: public void run() { long starttime = (new Date()).getTime(); Matcher m = Pattern.compile("(\\S+);(\\d+)").matcher(Destination); boolean completed = false; if (OutFile.length() > IncommingProcessor.MaxPayload) { logger.warn("Payload is too large!"); close(); } else { if (m.find()) { Runnable cl = new Runnable() { public void run() { WaitToClose(); } }; Thread t = new Thread(cl); t.start(); S = null; try { String ip = m.group(1); int port = Integer.valueOf(m.group(2)); SerpentEngine eng = new SerpentEngine(); byte[] keybytes = new byte[eng.getBlockSize()]; byte[] ivbytes = new byte[eng.getBlockSize()]; Random.nextBytes(keybytes); Random.nextBytes(ivbytes); KeyParameter keyparm = new KeyParameter(keybytes); ParametersWithIV keyivparm = new ParametersWithIV(keyparm, ivbytes); byte[] parmbytes = BCUtils.writeParametersWithIV(keyivparm); OAEPEncoding enc = new OAEPEncoding(new ElGamalEngine(), new RIPEMD128Digest()); enc.init(true, PublicKey); byte[] encbytes = enc.encodeBlock(parmbytes, 0, parmbytes.length); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine())); cipher.init(true, keyivparm); byte[] inbuffer = new byte[128]; byte[] outbuffer = new byte[256]; int readlen = 0; int cryptlen = 0; FileInputStream fis = new FileInputStream(OutFile); FileOutputStream fos = new FileOutputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { if (readlen > 0) { cryptlen = cipher.processBytes(inbuffer, 0, readlen, outbuffer, 0); fos.write(outbuffer, 0, cryptlen); } readlen = fis.read(inbuffer); } cryptlen = cipher.doFinal(outbuffer, 0); if (cryptlen > 0) { fos.write(outbuffer, 0, cryptlen); } fos.close(); fis.close(); S = new Socket(ip, port); DataOutputStream dos = new DataOutputStream(S.getOutputStream()); dos.writeInt(encbytes.length); dos.write(encbytes); dos.writeLong(TmpFile.length()); fis = new FileInputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { dos.write(inbuffer, 0, readlen); readlen = fis.read(inbuffer); } DataInputStream dis = new DataInputStream(S.getInputStream()); byte[] encipbytes = StreamUtils.readBytes(dis); cipher.init(false, keyivparm); byte[] decipbytes = new byte[encipbytes.length]; int len = cipher.processBytes(encipbytes, 0, encipbytes.length, decipbytes, 0); len += cipher.doFinal(decipbytes, len); byte[] realbytes = new byte[len]; System.arraycopy(decipbytes, 0, realbytes, 0, len); String ipstr = new String(realbytes, "ISO-8859-1"); Callback.Success(ipstr); completed = true; dos.write(0); dos.flush(); close(); } catch (Exception e) { close(); if (!completed) { e.printStackTrace(); Callback.Fail(e.getMessage()); } } } else { close(); logger.warn("Improper destination string. " + Destination); Callback.Fail("Improper destination string. " + Destination); } } CloseWait(); long newtime = (new Date()).getTime(); long timediff = newtime - starttime; logger.debug("Outgoing processor took: " + timediff); } Code Sample 2: public boolean updateCalculatedHand(CalculateTransferObject query, BasicStartingHandTransferObject[] hands) throws CalculateDAOException { boolean retval = false; Connection connection = null; Statement statement = null; PreparedStatement prep = null; ResultSet result = null; StringBuffer sql = new StringBuffer(SELECT_ID_SQL); sql.append(appendQuery(query)); try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); statement = connection.createStatement(); result = statement.executeQuery(sql.toString()); if (result.first()) { String id = result.getString("id"); prep = connection.prepareStatement(UPDATE_HANDS_SQL); for (int i = 0; i < hands.length; i++) { prep.setInt(1, hands[i].getWins()); prep.setInt(2, hands[i].getLoses()); prep.setInt(3, hands[i].getDraws()); prep.setString(4, id); prep.setString(5, hands[i].getHand()); if (prep.executeUpdate() != 1) { throw new SQLException("updated too many records in calculatehands, " + id + "-" + hands[i].getHand()); } } connection.commit(); } } catch (SQLException sqle) { try { connection.rollback(); } catch (SQLException e) { e.setNextException(sqle); throw new CalculateDAOException(e); } throw new CalculateDAOException(sqle); } finally { if (result != null) { try { result.close(); } catch (SQLException e) { throw new CalculateDAOException(e); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { throw new CalculateDAOException(e); } } if (prep != null) { try { prep.close(); } catch (SQLException e) { throw new CalculateDAOException(e); } } } return retval; }
11
Code Sample 1: private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } } Code Sample 2: public void saveToPackage() { boolean inPackage = false; String className = IconEditor.className; if (!checkPackage()) { JOptionPane.showMessageDialog(this, "No package selected. Aborting.", "Package not selected!", JOptionPane.WARNING_MESSAGE); return; } File iconFile = new File(getPackageFile().getParent() + File.separator + classIcon); File prevIconFile = new File(prevPackagePath + File.separator + classIcon); if ((IconEditor.getClassIcon() == null) || !prevIconFile.exists()) { IconEditor.setClassIcon("default.gif"); } else if (prevIconFile.exists() && (prevIconFile.compareTo(iconFile) != 0)) { FileFuncs.copyImageFile(prevIconFile, iconFile); } ci = new ClassImport(getPackageFile(), packageClassNamesList, packageClassList); for (int i = 0; i < packageClassList.size(); i++) { if (IconEditor.className.equalsIgnoreCase(packageClassList.get(i).getName())) { inPackage = true; classX = 0 - classX; classY = 0 - classY; shapeList.shift(classX, classY); packageClassList.get(i).setBoundingbox(boundingbox); packageClassList.get(i).setDescription(IconEditor.classDescription); if (IconEditor.getClassIcon() == null) { packageClassList.get(i).setIconName("default.gif"); } else { packageClassList.get(i).setIconName(IconEditor.getClassIcon()); } packageClassList.get(i).setIsRelation(IconEditor.classIsRelation); packageClassList.get(i).setName(IconEditor.className); packageClassList.get(i).setPorts(ports); packageClassList.get(i).shiftPorts(classX, classY); packageClassList.get(i).setShapeList(shapeList); if (dbrClassFields != null && dbrClassFields.getRowCount() > 0) { fields.clear(); for (int j = 0; j < dbrClassFields.getRowCount(); j++) { String fieldName = dbrClassFields.getValueAt(j, iNAME); String fieldType = dbrClassFields.getValueAt(j, iTYPE); String fieldValue = dbrClassFields.getValueAt(j, iVALUE); ClassField field = new ClassField(fieldName, fieldType, fieldValue); fields.add(field); } } packageClassList.get(i).setFields(fields); packageClassList.add(packageClassList.get(i)); packageClassList.remove(i); break; } } try { BufferedReader in = new BufferedReader(new FileReader(getPackageFile())); String str; StringBuffer content = new StringBuffer(); while ((str = in.readLine()) != null) { if (inPackage && str.trim().startsWith("<class")) { break; } else if (!inPackage) { if (str.equalsIgnoreCase("</package>")) break; content.append(str + "\n"); } else if (inPackage) content.append(str + "\n"); } if (!inPackage) { content.append(getShapesInXML(false)); } else { for (int i = 0; i < packageClassList.size(); i++) { classX = 0; classY = 0; makeClass(packageClassList.get(i)); content.append(getShapesInXML(false)); } } content.append("</package>"); in.close(); File javaFile = new File(getPackageFile().getParent() + File.separator + className + ".java"); File prevJavaFile = new File(prevPackagePath + File.separator + className + ".java"); int overwriteFile = JOptionPane.YES_OPTION; if (javaFile.exists()) { overwriteFile = JOptionPane.showConfirmDialog(null, "Java class already exists. Overwrite?"); } if (overwriteFile != JOptionPane.CANCEL_OPTION) { FileOutputStream out = new FileOutputStream(new File(getPackageFile().getAbsolutePath())); out.write(content.toString().getBytes()); out.flush(); out.close(); if (overwriteFile == JOptionPane.YES_OPTION) { String fileText = null; if (prevJavaFile.exists()) { fileText = FileFuncs.getFileContents(prevJavaFile); } else { fileText = "class " + className + " {"; fileText += "\n /*@ specification " + className + " {\n"; for (int i = 0; i < dbrClassFields.getRowCount(); i++) { String fieldName = dbrClassFields.getValueAt(i, iNAME); String fieldType = dbrClassFields.getValueAt(i, iTYPE); if (fieldType != null) { fileText += " " + fieldType + " " + fieldName + ";\n"; } } fileText += " }@*/\n \n}"; } FileFuncs.writeFile(javaFile, fileText); } JOptionPane.showMessageDialog(null, "Saved to package: " + getPackageFile().getName(), "Saved", JOptionPane.INFORMATION_MESSAGE); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private void processOrder() { double neg = 0d; if (intMode == MODE_CHECKOUT) { if (round2Places(mBuf.getBufferTotal()) >= round2Places(order.getOrderTotal())) { double cash, credit, allowedCredit = 0d; allowedCredit = getStudentCredit(); if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { try { neg = Double.parseDouble(settings.get(DBSettings.MAIN_MAXNEGBALANCE)); } catch (NumberFormatException ex) { System.err.println("NumberFormatException::Potential problem with setting MAIN_MAXNEGBALANCE"); System.err.println(" * Note: If you enable negative balances, please don't leave this"); System.err.println(" blank. At least set it to 0. For right now we are setting "); System.err.println(" the max negative balance to $0.00"); System.err.println(""); System.err.println("Exception Message:" + ex.getMessage()); } if (neg < 0) neg *= -1; allowedCredit += neg; } if (round2Places(mBuf.getCredit()) <= round2Places(allowedCredit)) { if (round2Places(mBuf.getCredit()) > round2Places(getStudentCredit()) && !student.isStudentSet()) { gui.setStatus("Can't allow negative balance on an anonymous student!", true); } else { if (round2Places(mBuf.getCredit()) > round2Places(order.getOrderTotal())) { credit = round2Places(order.getOrderTotal()); } else { credit = round2Places(mBuf.getCredit()); } if ((mBuf.getCash() + credit) >= order.getOrderTotal()) { cash = round2Places(order.getOrderTotal() - credit); double change = round2Places(mBuf.getCash() - cash); if (round2Places(cash + credit) == round2Places(order.getOrderTotal())) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = dbMan.getPOSConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String host = getHostName(); String stuId = student.getStudentNumber(); String building = settings.get(DBSettings.MAIN_BUILDING); String cashier = dbMan.getPOSUser(); String strSql = "insert into " + strPOSPrefix + "trans_master ( tm_studentid, tm_total, tm_cashtotal, tm_credittotal, tm_building, tm_register, tm_cashier, tm_datetime, tm_change ) values( '" + stuId + "', '" + round2Places(order.getOrderTotal()) + "', '" + round2Places(cash) + "', '" + round2Places(credit) + "', '" + building + "', '" + host + "', '" + cashier + "', NOW(), '" + round2Places(change) + "')"; int intSqlReturnVal = -1; int masterID = -1; try { intSqlReturnVal = stmt.executeUpdate(strSql, Statement.RETURN_GENERATED_KEYS); ResultSet keys = stmt.getGeneratedKeys(); keys.next(); masterID = keys.getInt(1); keys.close(); stmt.close(); } catch (Exception exRetKeys) { System.err.println(exRetKeys.getMessage() + " (but pscafepos is attempting a work around)"); intSqlReturnVal = stmt.executeUpdate(strSql); masterID = dbMan.getLastInsertIDWorkAround(stmt, strPOSPrefix + "trans_master_tm_id_seq"); if (masterID == -1) System.err.println("It looks like the work around failed, please submit a bug report!"); else System.err.println("work around was successful!"); } if (intSqlReturnVal == 1) { if (masterID >= 0) { OrderItem[] itms = order.getOrderItems(); if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { if (itms[i] != null) { stmt = conn.createStatement(); int itemid = itms[i].getDBID(); double itemprice = round2Places(itms[i].getEffectivePrice()); int f, r, a; String strItemName, strItemBuilding, strItemCat; f = 0; r = 0; a = 0; if (itms[i].isSoldAsFree()) { f = 1; } if (itms[i].isSoldAsReduced()) { r = 1; } if (itms[i].isTypeA()) { a = 1; } strItemName = itms[i].getName(); strItemBuilding = (String) itms[i].getBuilding(); strItemCat = itms[i].getCategory(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "trans_item ( ti_itemid, ti_tmid, ti_pricesold, ti_registerid, ti_cashier, ti_studentid, ti_isfree, ti_isreduced, ti_datetime, ti_istypea, ti_itemname, ti_itembuilding, ti_itemcat ) values('" + itemid + "', '" + masterID + "', '" + round2Places(itemprice) + "', '" + host + "', '" + cashier + "', '" + stuId + "', '" + f + "', '" + r + "', NOW(), '" + a + "', '" + strItemName + "', '" + strItemBuilding + "', '" + strItemCat + "')") != 1) { gui.setCriticalMessage("Item insert failed"); conn.rollback(); } stmt.close(); stmt = conn.createStatement(); String sqlInv = "SELECT inv_id from " + strPOSPrefix + "inventory where inv_menuid = " + itemid + ""; if (stmt.execute(sqlInv)) { ResultSet rsInv = stmt.getResultSet(); int delId = -1; if (rsInv.next()) { delId = rsInv.getInt("inv_id"); } if (delId != -1) { stmt.executeUpdate("delete from " + strPOSPrefix + "inventory where inv_id = " + delId); } stmt.close(); } } else { gui.setCriticalMessage("Null Item"); conn.rollback(); } } boolean blOk = true; if (round2Places(credit) > 0d) { if (round2Places(allowedCredit) >= round2Places(credit)) { if (hasStudentCredit()) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "studentcredit set credit_amount = credit_amount - " + round2Places(credit) + " where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "studentcredit set credit_lastused = NOW() where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to update student credit account."); blOk = false; } } else { gui.setCriticalMessage("Unable to update student credit account."); blOk = false; } } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit (credit_amount,credit_active,credit_studentid,credit_lastused) values('" + round2Places((-1) * credit) + "','1','" + stuId + "', NOW())") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to create new student credit account."); blOk = false; } } } else { gui.setCriticalMessage("Student doesn't have enought credit."); blOk = false; } } if (blOk) { if (blDepositCredit && change > 0d) { try { if (doStudentCreditUpdate(change, stuId)) { change = 0d; } else blOk = false; } catch (Exception cExp) { blOk = false; } } } if (blOk) { boolean blHBOK = true; if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { stmt = conn.createStatement(); if (stmt.execute("select count(*) from " + strPOSPrefix + "hotbar where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'")) { rs = stmt.getResultSet(); rs.next(); int num = rs.getInt(1); stmt.close(); if (num == 1) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "hotbar set hb_count = hb_count + 1 where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'") != 1) blHBOK = false; } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "hotbar ( hb_itemid, hb_building, hb_register, hb_cashier, hb_count ) values( '" + itms[i].getDBID() + "', '" + building + "', '" + host + "', '" + cashier + "', '1' )") != 1) blHBOK = false; } stmt.close(); } } } else blHBOK = false; if (blHBOK) { conn.commit(); gui.setStatus("Order Complete."); gui.disableUI(); summary = new PSOrderSummary(gui); if (cashDrawer != null) cashDrawer.openDrawer(); else summary.setPOSEventListener(this); summary.display(money.format(order.getOrderTotal()), money.format(mBuf.getCash()), money.format(credit), money.format(change), money.format(getStudentCredit())); } else { conn.rollback(); gui.setStatus("Failure during Hotbar update. Transaction has been rolled back.", true); } } else { conn.rollback(); } } else { gui.setCriticalMessage("Unable to fetch items."); conn.rollback(); } } else { gui.setCriticalMessage("Unable to retrieve autoid"); conn.rollback(); } } else { gui.setCriticalMessage("Error During Writting of Transaction Master Record."); conn.rollback(); } } catch (SQLException sqlEx) { System.err.println("SQLException: " + sqlEx.getMessage()); System.err.println("SQLState: " + sqlEx.getSQLState()); System.err.println("VendorError: " + sqlEx.getErrorCode()); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { stmt = null; } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); } } } } } } else { gui.setStatus("Credit total + Cash total is less then the order total! ", true); } } } else { if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { gui.setStatus("Sorry, maximum negative balance is " + money.format(neg) + "!", true); } else gui.setStatus("Student does not have enough credit to process this order.", true); } } else { gui.setStatus("Buffer total is less then the order total.", true); } } } Code Sample 2: @Test public void testConfigurartion() { try { Enumeration<URL> assemblersToRegister = this.getClass().getClassLoader().getResources("META-INF/PrintAssemblerFactory.properties"); log.debug("PrintAssemblerFactory " + SimplePrintJobTest.class.getClassLoader().getResource("META-INF/PrintAssemblerFactory.properties")); log.debug("ehcache " + SimplePrintJobTest.class.getClassLoader().getResource("ehcache.xml")); log.debug("log4j " + this.getClass().getClassLoader().getResource("/log4j.xml")); if (log.isDebugEnabled()) { while (assemblersToRegister.hasMoreElements()) { URL url = (URL) assemblersToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); line = buff.readLine(); } buff.close(); in.close(); } } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static JSONObject delete(String uid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(DELETE_URI + "?uid=" + uid); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); } Code Sample 2: public static void main(String argv[]) { System.out.println("Starting URL tests"); System.out.println("Test 1: Simple URL test"); try { URL url = new URL("http", "www.fsf.org", 80, "/"); if (!url.getProtocol().equals("http") || !url.getHost().equals("www.fsf.org") || url.getPort() != 80 || !url.getFile().equals("/")) System.out.println("FAILED: Simple URL test"); System.out.println("URL is: " + url.toString()); URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) System.out.println("Got the expected connection type"); HttpURLConnection hc = (HttpURLConnection) uc; hc.connect(); System.out.flush(); System.out.println("Dumping response headers"); for (int i = 0; ; i++) { String key = hc.getHeaderFieldKey(i); if (key == null) break; System.out.println(key + ": " + hc.getHeaderField(i)); } System.out.flush(); System.out.println("Dumping contents"); BufferedReader br = new BufferedReader(new InputStreamReader(hc.getInputStream())); for (String str = br.readLine(); str != null; str = br.readLine()) { System.out.println(str); } System.out.flush(); hc.disconnect(); System.out.println("Content Type: " + hc.getContentType()); System.out.println("Content Encoding: " + hc.getContentEncoding()); System.out.println("Content Length: " + hc.getContentLength()); System.out.println("Date: " + hc.getDate()); System.out.println("Expiration: " + hc.getExpiration()); System.out.println("Last Modified: " + hc.getLastModified()); System.out.println("PASSED: Simple URL test"); } catch (IOException e) { System.out.println("FAILED: Simple URL test: " + e); } System.out.println("Test 2: URL parsing test"); try { URL url = new URL("http://www.urbanophile.com/arenn/trans/trans.html#mis"); if (!url.toString().equals("http://www.urbanophile.com/arenn/trans/trans.html#mis")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("http://www.foo.com:8080/#"); if (!url.toString().equals("http://www.foo.com:8080/#")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("http://www.bar.com/test:file/"); if (!url.toString().equals("http://www.bar.com/test:file/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("http://www.gnu.org"); if (!url.toString().equals("http://www.gnu.org/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("HTTP://www.fsf.org/"); if (!url.toString().equals("http://www.fsf.org/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); System.out.println("PASSED: URL parse test"); } } } } } } catch (IOException e) { System.out.println("FAILED: URL parsing test: " + e); } System.out.println("Test 3: getContent test"); try { URL url = new URL("http://localhost/~arenn/services.txt"); Object obj = url.getContent(); System.out.println("Object type is: " + obj.getClass().getName()); if (obj instanceof InputStream) { System.out.println("Got InputStream, so dumping contents"); BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) obj)); for (String str = br.readLine(); str != null; str = br.readLine()) System.out.println(str); br.close(); } else { System.out.println("FAILED: Object is not an InputStream"); } System.out.println("PASSED: getContent test"); } catch (IOException e) { System.out.println("FAILED: getContent test: " + e); } System.out.println("URL test complete"); }
11
Code Sample 1: public void xtest12() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf"); InputStream page1 = manager.cut(pdf, 36, 36); OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); } Code Sample 2: public Object read(InputStream inputStream, Map metadata) throws IOException, ClassNotFoundException { if (log.isTraceEnabled()) log.trace("Read input stream with metadata=" + metadata); Integer resCode = (Integer) metadata.get(HTTPMetadataConstants.RESPONSE_CODE); String resMessage = (String) metadata.get(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE); if (resCode != null && validResponseCodes.contains(resCode) == false) throw new RuntimeException("Invalid HTTP server response [" + resCode + "] - " + resMessage); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); String soapMessage = new String(baos.toByteArray(), charsetEncoding); if (isTraceEnabled) { String prettySoapMessage = DOMWriter.printNode(DOMUtils.parse(soapMessage), true); log.trace("Incoming Response SOAPMessage\n" + prettySoapMessage); } return soapMessage; }
00
Code Sample 1: public static final String MD5(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String newValue = hash.toString(16); return newValue; } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return null; } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public void moveRowUp(int id, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt, id); if ((row < 2) || (row > max)) throw new IllegalArgumentException("Row number not between 2 and " + max); stmt.executeUpdate("update InstructionGroups set Rank = -1 where InstructionId = '" + id + "' and Rank = " + row); stmt.executeUpdate("update InstructionGroups set Rank = " + row + " where InstructionId = '" + id + "' and Rank = " + (row - 1)); stmt.executeUpdate("update InstructionGroups set Rank = " + (row - 1) + " where InstructionId = '" + id + "' and Rank = -1"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
11
Code Sample 1: public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); } 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 static int fileUpload(long lngFileSize, InputStream inputStream, String strFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); if (lngFileSize > (10 * 1024 * 1024)) { return -1; } InputStream is = null; FileOutputStream fos = null; try { File dir = new File(strFilePath); if (!dir.exists()) dir.mkdirs(); is = inputStream; fos = new FileOutputStream(new File(strFilePath + SEPARATOR + strFileName)); IOUtils.copy(is, fos); } catch (Exception ex) { return -2; } finally { try { fos.close(); is.close(); } catch (Exception ex2) { } } return 0; } Code Sample 2: public static byte[] sendRequestV1(String url, Map<String, Object> params, String secretCode, String method, Map<String, String> files, String encoding, String signMethod, Map<String, String> headers, String contentType) { HttpClient client = new HttpClient(); byte[] result = null; if (method.equalsIgnoreCase("get")) { GetMethod getMethod = new GetMethod(url); if (contentType == null || contentType.equals("")) getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); else getMethod.setRequestHeader("Content-Type", contentType); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); getMethod.setRequestHeader(key, headers.get(key)); } } try { NameValuePair[] getData; if (params != null) { if (secretCode == null) getData = new NameValuePair[params.size()]; else getData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); getData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature2(params, secretCode, "md5".equalsIgnoreCase(signMethod), isHMac, PARAMETER_SIGN); getData[i] = new NameValuePair(PARAMETER_SIGN, sign); } getMethod.setQueryString(getData); } client.executeMethod(getMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = getMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (bout != null) bout.close(); } } catch (Exception ex) { logger.error(ex, ex); } finally { if (getMethod != null) getMethod.releaseConnection(); } } if (method.equalsIgnoreCase("post")) { PostMethod postMethod = new PostMethod(url); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); postMethod.setRequestHeader(key, headers.get(key)); } } try { if (contentType == null) { if (files != null && files.size() > 0) { Part[] parts; if (secretCode == null) parts = new Part[params.size() + files.size()]; else parts = new Part[params.size() + 1 + files.size()]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); parts[i] = new StringPart(key, params.get(key).toString(), "UTF-8"); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); parts[i] = new StringPart(PARAMETER_SIGN, sign); i++; } iters = files.keySet().iterator(); while (iters.hasNext()) { String key = (String) iters.next(); if (files.get(key).toString().startsWith("http://")) { InputStream bin = null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { URL fileurl = new URL(files.get(key).toString()); bin = fileurl.openStream(); byte[] buf = new byte[500]; int count = 0; while ((count = bin.read(buf)) > 0) { bout.write(buf, 0, count); } parts[i] = new FilePart(key, new ByteArrayPartSource(fileurl.getFile().substring(fileurl.getFile().lastIndexOf("/") + 1), bout.toByteArray())); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bin != null) bin.close(); if (bout != null) bout.close(); } } else parts[i] = new FilePart(key, new File(files.get(key).toString())); i++; } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else { NameValuePair[] postData; if (params != null) { if (secretCode == null) postData = new NameValuePair[params.size()]; else postData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); postData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); postData[i] = new NameValuePair(PARAMETER_SIGN, sign); } postMethod.setRequestBody(postData); } if (contentType == null || contentType.equals("")) postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); } } else { String content = (String) params.get(params.keySet().iterator().next()); RequestEntity entiry = new StringRequestEntity(content, contentType, "UTF-8"); postMethod.setRequestEntity(entiry); } client.executeMethod(postMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = postMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bout != null) bout.close(); } } catch (Exception e) { logger.error(e, e); } finally { if (postMethod != null) postMethod.releaseConnection(); } } return result; }
11
Code Sample 1: public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); } Code Sample 2: 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 { } }
00
Code Sample 1: @Override protected void setUp() throws Exception { super.setUp(); FTPConf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); FTPConf.setServerTimeZoneId("GMT"); FTP.configure(FTPConf); try { FTP.connect("tgftp.nws.noaa.gov"); FTP.login("anonymous", "[email protected]"); FTP.changeWorkingDirectory("SL.us008001/DF.an/DC.sflnd/DS.metar"); FTP.enterLocalPassiveMode(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); }
00
Code Sample 1: public void SendFile(File testfile) { try { SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234)); sock.configureBlocking(true); while (!sock.finishConnect()) { System.out.println("NOT connected!"); } System.out.println("CONNECTED!"); FileInputStream fis = new FileInputStream(testfile); FileChannel fic = fis.getChannel(); long len = fic.size(); Buffer.clear(); Buffer.putLong(len); Buffer.flip(); sock.write(Buffer); long cnt = 0; while (cnt < len) { Buffer.clear(); int add = fic.read(Buffer); cnt += add; Buffer.flip(); while (Buffer.hasRemaining()) { sock.write(Buffer); } } fic.close(); File tmpfile = getTmp().createNewFile("tmp", "tmp"); FileOutputStream fos = new FileOutputStream(tmpfile); FileChannel foc = fos.getChannel(); int mlen = -1; do { Buffer.clear(); mlen = sock.read(Buffer); Buffer.flip(); if (mlen > 0) { foc.write(Buffer); } } while (mlen > 0); foc.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static String readRss(String feed, int num) { InputStream stream = null; try { feed = appendParam(feed, "num", "" + num); System.out.println("feed=" + feed); URL url = new URL(feed); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", RSS_USER_AGENT); stream = connection.getInputStream(); return CFileHelper.readInputStream(stream); } catch (Exception e) { throw new CException(e); } finally { CFileHelper.closeStream(stream); } }
11
Code Sample 1: public static void CreateBackupOfDataFile(String _src, String _dest) { try { File src = new File(_src); File dest = new File(_dest); if (new File(_src).exists()) { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } File directory = new File("lib/"); File dest = new File(directory, file.getName()); File parent = dest.getParentFile(); while (parent != null && !parent.equals(directory)) { parent = parent.getParentFile(); } if (parent.equals(directory)) { return file; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return dest; }
00
Code Sample 1: public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public 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); }
00
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static String encrypt(String text) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String result = ""; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes()); byte[] hash = digest.digest(); char buffer[] = new char[hash.length * 2]; for (int i = 0, x = 0; i < hash.length; i++) { buffer[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; buffer[x++] = HEX_CHARS[hash[i] & 0xf]; } result = new String(buffer); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
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 copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: private long config(final String options) throws SQLException { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } msgDigest.update(options.getBytes()); final String md5sum = Concrete.md5(msgDigest.digest()); Statement stmt = connection.createStatement(); ResultSet rst = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + md5sum + "'"); final long configId; if (rst.next()) { configId = rst.getInt(1); } else { stmt.executeUpdate("INSERT INTO configs(config, md5) VALUES ('" + options + "', '" + md5sum + "')"); ResultSet aiRst = stmt.getGeneratedKeys(); if (aiRst.next()) { configId = aiRst.getInt(1); } else { throw new SQLException("Could not retrieve generated id"); } } stmt.executeUpdate("UPDATE executions SET configId=" + configId + " WHERE executionId=" + executionId); return configId; } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
00
Code Sample 1: public HttpResponse executeHttp(final HttpUriRequest request, final int expectedCode) throws ClientProtocolException, IOException, HttpException { final HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != expectedCode) { throw newHttpException(request, response); } return response; } Code Sample 2: public MultiValueMap<String> queryResource(String resourceName) { if (resourceName.startsWith("http://dbpedia.org/resource/")) { resourceName = resourceName.substring(28); } try { resourceName = resourceName.replace(' ', '_'); resourceName = URLEncoder.encode(resourceName, "UTF-8"); } catch (UnsupportedEncodingException exc) { } String select = prefix + " SELECT ?property ?hasValue WHERE { { " + "<http://dbpedia.org/resource/" + resourceName + "> ?property ?hasValue } FILTER (lang(?hasValue) = \"" + lang + "\" || !isLiteral(?hasValue))}"; System.out.println(select); MultiValueMap<String> resourceMap = new MultiValueMap<String>(); try { URL url = new URL(queryBase + URLEncoder.encode(select, "UTF-8")); InputStream inStream = url.openStream(); Document doc = docBuild.parse(inStream); Element table = doc.getDocumentElement(); NodeList rows = table.getElementsByTagName("tr"); for (int i = 0; i < rows.getLength(); i++) { Element row = (Element) rows.item(i); NodeList cols = row.getElementsByTagName("td"); if (cols.getLength() > 1) { Element propElem = (Element) cols.item(0); Element valElem = (Element) cols.item(1); String property = ((Text) propElem.getFirstChild()).getData(); if (property.startsWith("http://dbpedia.org/property/")) { property = property.substring(28); } else { int inx = property.indexOf('#'); if (inx == -1) { inx = property.lastIndexOf('/'); } property = property.substring(inx + 1); } String value = ((Text) valElem.getFirstChild()).getData(); if (value.startsWith("http://dbpedia.org/resource/")) { value = value.substring(28).replaceAll("_", " "); } resourceMap.addFieldValue(property, value); } } } catch (UnsupportedEncodingException exc) { exc.printStackTrace(); } catch (IOException exc) { System.err.println("Cannot retrieve record for " + resourceName); } catch (SAXException exc) { System.err.println("Cannot parse record for " + resourceName); } return resourceMap; }
00
Code Sample 1: private Date getArtifactFileLastUpdate(Artifact artifact) { URL url = null; try { url = new URL(baseUrl + artifact.getOrganisationName().replaceAll("\\.", "/") + "/" + artifact.getName().replaceAll("\\.", "/") + "/" + artifact.getVersion() + "/"); } catch (MalformedURLException e) { log.warn("cannot retrieve last modifcation date", e); return null; } URLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); } catch (FileNotFoundException e) { log.warn("cannot retrieve last modifcation date", e); return null; } catch (IOException e) { log.warn("cannot retrieve last modifcation date", e); return null; } StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; try { while ((line = reader.readLine()) != null) { buffer.append(line); } } catch (IOException e) { log.warn("cannot retrieve last modifcation date", e); return new Date(0); } Pattern pattern = Pattern.compile("<a href=\"" + artifact.getName() + "-" + artifact.getVersion() + ".jar\">" + artifact.getName() + "-" + artifact.getVersion() + ".jar</a> *(\\d{2}-[a-zA-Z]{3}-\\d{4} \\d{2}:\\d{2})"); Matcher m = pattern.matcher(buffer); if (m.find()) { String dateStr = m.group(1); try { return mavenDateFormateur.parse(dateStr); } catch (ParseException e) { log.warn("cannot retrieve last modifcation date", e); return new Date(0); } } log.warn("cannot retrieve last modifcation date"); return new Date(0); } Code Sample 2: public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
00
Code Sample 1: @Override public void write(OutputStream output) throws IOException, WebApplicationException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOs = new GZIPOutputStream(baos); IOUtils.copy(is, gzipOs); baos.close(); gzipOs.close(); output.write(baos.toByteArray()); } Code Sample 2: public void lock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setString(1, key); ps.setLong(2, System.currentTimeMillis()); ps.setString(3, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to lock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
11
Code Sample 1: public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { noSuchAlgorithmException.printStackTrace(); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException unsupportedEncodingException) { unsupportedEncodingException.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public boolean WriteFile(java.io.Serializable inObj, String fileName) throws Exception { FileOutputStream out; try { SecretKey skey = null; AlgorithmParameterSpec aps; out = new FileOutputStream(fileName); cipher = Cipher.getInstance(algorithm); KeySpec kspec = new PBEKeySpec(filePasswd.toCharArray()); SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm); skey = skf.generateSecret(kspec); MessageDigest md = MessageDigest.getInstance(res.getString("MD5")); md.update(filePasswd.getBytes()); byte[] digest = md.digest(); System.arraycopy(digest, 0, salt, 0, 8); aps = new PBEParameterSpec(salt, iterations); out.write(salt); ObjectOutputStream s = new ObjectOutputStream(out); cipher.init(Cipher.ENCRYPT_MODE, skey, aps); SealedObject so = new SealedObject(inObj, cipher); s.writeObject(so); s.flush(); out.close(); } catch (Exception e) { Log.out("fileName=" + fileName); Log.out("algorithm=" + algorithm); Log.out(e); throw e; } return true; }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; }
00
Code Sample 1: public TwilioRestResponse request(String path, String method, Map<String, String> vars) throws TwilioRestException { String encoded = ""; if (vars != null) { for (String key : vars.keySet()) { try { encoded += "&" + key + "=" + URLEncoder.encode(vars.get(key), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } if (encoded.length() > 0) { encoded = encoded.substring(1); } } String url = this.endpoint + path; if (method.toUpperCase().equals("GET")) url += ((path.indexOf('?') == -1) ? "?" : "&") + encoded; try { URL resturl = new URL(url); HttpURLConnection con = (HttpURLConnection) resturl.openConnection(); String userpass = this.accountSid + ":" + this.authToken; String encodeuserpass = new String(Base64.encodeToByte(userpass.getBytes(), false)); con.setRequestProperty("Authorization", "Basic " + encodeuserpass); con.setDoOutput(true); if (method.toUpperCase().equals("GET")) { con.setRequestMethod("GET"); } else if (method.toUpperCase().equals("POST")) { con.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("PUT")) { con.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("DELETE")) { con.setRequestMethod("DELETE"); } else { throw new TwilioRestException("Unknown method " + method); } BufferedReader in = null; try { if (con.getInputStream() != null) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } } catch (IOException e) { if (con.getErrorStream() != null) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } } if (in == null) { throw new TwilioRestException("Unable to read response from server"); } StringBuffer decodedString = new StringBuffer(); String line; while ((line = in.readLine()) != null) { decodedString.append(line); } in.close(); int responseCode = con.getResponseCode(); return new TwilioRestResponse(url, decodedString.toString(), responseCode); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
11
Code Sample 1: public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } Code Sample 2: public static String getMD5Hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); String hexChar = ""; for (int i = 0; i < hash.length; i++) { hexChar = Integer.toHexString(0xFF & hash[i]); if (hexChar.length() < 2) { hexChar = "0" + hexChar; } hexString.append(hexChar); } return hexString.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
00
Code Sample 1: public <T extends FetionResponse> T executeAction(FetionAction<T> fetionAction) throws IOException { URL url = new URL(fetionAction.getProtocol().name().toLowerCase() + "://" + fetionUrl + fetionAction.getRequestData()); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); byte[] buffer = new byte[10240]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int read = 0; while ((read = in.read(buffer)) > 0) { bout.write(buffer, 0, read); } return fetionAction.processResponse(parseRawResponse(bout.toByteArray())); } Code Sample 2: public static void writeInputStreamToFile(final InputStream stream, final File target) { long size = 0; FileOutputStream fileOut; try { fileOut = new FileOutputStream(target); size = IOUtils.copyLarge(stream, fileOut); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (log.isInfoEnabled()) { log.info("Wrote " + size + " bytes to " + target.getAbsolutePath()); } else { System.out.println("Wrote " + size + " bytes to " + target.getAbsolutePath()); } }
00
Code Sample 1: public String md5(String phrase) { MessageDigest m; String coded = new String(); try { m = MessageDigest.getInstance("MD5"); m.update(phrase.getBytes(), 0, phrase.length()); coded = (new BigInteger(1, m.digest()).toString(16)).toString(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } if (coded.length() < 32) { coded = "0" + coded; } return coded; } Code Sample 2: private void copy(File src, File dest, String name) { File srcFile = new File(src, name); File destFile = new File(dest, name); if (destFile.exists()) { if (destFile.lastModified() == srcFile.lastModified()) return; destFile.delete(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(srcFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } } destFile.setLastModified(srcFile.lastModified()); }
11
Code Sample 1: public void sendMessage(Message msg) { if (!blackList.contains(msg.getTo())) { Hashtable<String, String> content = msg.getContent(); Enumeration<String> keys = content.keys(); String key; String data = "to=" + msg.getTo() + "&from=" + msg.getFrom() + "&"; while (keys.hasMoreElements()) { key = (String) keys.nextElement(); data += key + "=" + content.get(key) + "&"; } URL url = null; try { logger.log(this, Level.FINER, "sending " + data + " to " + msg.getTo()); url = new URL("http://" + msg.getTo() + ":8080/webmsgservice?" + data); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); in.readLine(); in.close(); logger.log(this, Level.FINER, "message sent to " + msg.getTo()); } catch (MalformedURLException e) { blackList.add(msg.getTo()); logger.log(this, Level.WARNING, "an error occured during message sending (" + msg.getTo() + ") : " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { logger.log(this, Level.WARNING, "an error occured during message sending (" + msg.getTo() + ") : " + e.getMessage()); blackList.add(msg.getTo()); } } else { logger.log(this, Level.FINE, "will not send message to " + msg.getTo() + " because black listed IP"); } } Code Sample 2: public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
11
Code Sample 1: private static void readIzvestiyaArticles() throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';'); reader.setTrimWhitespace(true); try { while (reader.readRecord()) { String id = reader.get(0); String filename = reader.get(1); StringTokenizer st = new StringTokenizer(filename, "-."); String name = st.nextToken(); String volume = st.nextToken(); String year = st.nextToken(); String extension = st.nextToken(); String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension); id2filename.put(id, filepath); } } finally { reader.close(); } for (Map.Entry<String, String> entry : id2filename.entrySet()) { String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue()); filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX"); if (new File(filepath).exists()) { InputStream in = new FileInputStream(filepath); FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false); try { org.apache.commons.io.IOUtils.copy(in, out); } catch (Exception e) { org.apache.commons.io.IOUtils.closeQuietly(in); org.apache.commons.io.IOUtils.closeQuietly(out); } } else { logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist"); } } } Code Sample 2: public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); } Code Sample 2: public static void copy(Object arg1, Object arg2) { Writer writer = null; Reader reader = null; InputStream inStream = null; OutputStream outStream = null; try { if (arg2 instanceof Writer) { writer = (Writer) arg2; if (arg1 instanceof Reader) { reader = (Reader) arg1; copy(reader, writer); } else if (arg1 instanceof String) { reader = new FileReader(new File((String) arg1)); copy(reader, writer); } else if (arg1 instanceof File) { reader = new FileReader((File) arg1); copy(reader, writer); } else if (arg1 instanceof URL) { copy(((URL) arg1).openStream(), writer); } else if (arg1 instanceof InputStream) { reader = new InputStreamReader((InputStream) arg1); copy(reader, writer); } else if (arg1 instanceof RandomAccessFile) { copy((RandomAccessFile) arg1, writer); } else { throw new TypeError("Invalid first argument to copy()"); } } else if (arg2 instanceof OutputStream) { outStream = (OutputStream) arg2; if (arg1 instanceof Reader) { copy((Reader) arg1, new OutputStreamWriter(outStream)); } else if (arg1 instanceof String) { inStream = new FileInputStream(new File((String) arg1)); copy(inStream, outStream); } else if (arg1 instanceof File) { inStream = new FileInputStream((File) arg1); copy(inStream, outStream); } else if (arg1 instanceof URL) { copy(((URL) arg1).openStream(), outStream); } else if (arg1 instanceof InputStream) { copy((InputStream) arg1, outStream); } else if (arg1 instanceof RandomAccessFile) { copy((RandomAccessFile) arg1, outStream); } else { throw new TypeError("Invalid first argument to copy()"); } } else if (arg2 instanceof RandomAccessFile) { RandomAccessFile out = (RandomAccessFile) arg2; if (arg1 instanceof Reader) { copy((Reader) arg1, out); } else if (arg1 instanceof String) { inStream = new FileInputStream(new File((String) arg1)); copy(inStream, out); } else if (arg1 instanceof File) { inStream = new FileInputStream((File) arg1); copy(inStream, out); } else if (arg1 instanceof URL) { copy(((URL) arg1).openStream(), out); } else if (arg1 instanceof InputStream) { copy((InputStream) arg1, out); } else if (arg1 instanceof RandomAccessFile) { copy((RandomAccessFile) arg1, out); } else { throw new TypeError("Invalid first argument to copy()"); } } else if (arg2 instanceof File || arg2 instanceof String) { File outFile = null; if (arg2 instanceof File) { outFile = (File) arg2; } else { outFile = new File((String) arg2); } outStream = new FileOutputStream(outFile); if (arg1 instanceof Reader) { copy((Reader) arg1, new OutputStreamWriter(outStream)); } else if (arg1 instanceof String) { inStream = new FileInputStream(new File((String) arg1)); copy(inStream, outStream); } else if (arg1 instanceof File) { inStream = new FileInputStream((File) arg1); copy(inStream, outStream); } else if (arg1 instanceof URL) { copy(((URL) arg1).openStream(), outStream); } else if (arg1 instanceof InputStream) { copy((InputStream) arg1, outStream); } else if (arg1 instanceof RandomAccessFile) { copy((RandomAccessFile) arg1, outStream); } else { throw new TypeError("Invalid first argument to copy()"); } } else { throw new TypeError("Invalid second argument to copy()"); } } catch (IOException e) { throw new IOError(e.getMessage(), e); } }
00
Code Sample 1: public static void decompressFile(File f) throws IOException { File target = new File(f.toString().substring(0, f.toString().length() - 3)); System.out.print("Decompressing: " + f.getName() + ".. "); long initialSize = f.length(); GZIPInputStream in = new GZIPInputStream(new FileInputStream(f)); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int read; while ((read = in.read(buf)) != -1) { fos.write(buf, 0, read); } System.out.println("Done."); fos.close(); in.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Decompressed size: " + endSize); } Code Sample 2: public static final String enCode(String algorithm, String string) { MessageDigest md; String result = ""; try { md = MessageDigest.getInstance(algorithm); md.update(string.getBytes()); result = binaryToString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException(); String inFileName = args[0]; String outFileName = args[1]; File fInput = new File(inFileName); Scanner in = null; try { in = new Scanner(fInput); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(outFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } while (in.hasNextLine()) { out.println(in.nextLine()); } in.close(); out.close(); } Code Sample 2: public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } }
11
Code Sample 1: public void writeToFile(File file, File source) throws IOException { BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file)); BufferedInputStream bin = new BufferedInputStream(new FileInputStream(source)); bin.skip(header.getHeaderEndingOffset()); for (long i = 0; i < this.streamLength; i++) { bout.write(bin.read()); } bin.close(); bout.close(); } Code Sample 2: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.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; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.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 (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.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 (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } }
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 long removePropertyInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, String propriete) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (propriete.equals(Metadata.TITLE)) { coreProperties.setTitle(""); } else if (propriete.equals(Metadata.AUTHOR)) { coreProperties.setCreator(""); } else if (propriete.equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(""); } else if (propriete.equals(Metadata.COMMENTS)) { coreProperties.setDescription(""); } else if (propriete.equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(""); } else if (propriete.equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(""); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(propriete)) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(propriete)) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } }
11
Code Sample 1: @Override protected Integer doInBackground() throws Exception { int numOfRows = 0; combinationMap = new HashMap<AnsweredQuestion, Integer>(); combinationMapReverse = new HashMap<Integer, AnsweredQuestion>(); LinkedHashSet<AnsweredQuestion> answeredQuestionSet = new LinkedHashSet<AnsweredQuestion>(); LinkedHashSet<Integer> studentSet = new LinkedHashSet<Integer>(); final String delimiter = ";"; final String typeToProcess = "F"; String line; String[] chunks = new String[9]; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); numOfRows++; if (chunks[2].equals(typeToProcess)) { answeredQuestionSet.add(new AnsweredQuestion(chunks[4], chunks[5])); studentSet.add(new Integer(chunks[0])); } } in.close(); int i = 0; Integer I; for (AnsweredQuestion pair : answeredQuestionSet) { I = new Integer(i++); combinationMap.put(pair, I); combinationMapReverse.put(I, pair); } matrix = new SparseObjectMatrix2D(answeredQuestionSet.size(), studentSet.size()); int lastStudentNumber = -1; AnsweredQuestion pair; in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); pair = null; if (chunks[2].equals(typeToProcess)) { if (Integer.parseInt(chunks[0]) != lastStudentNumber) { lastStudentNumber++; } pair = new AnsweredQuestion(chunks[4], chunks[5]); if (combinationMap.containsKey(pair)) { matrix.setQuick(combinationMap.get(pair), lastStudentNumber, Boolean.TRUE); } } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } supportVector = new int[combinationMap.size()]; ObjectMatrix1D row = null; for (int i = 0; i < combinationMap.size(); i++) { row = matrix.viewRow(i); int sum = 0; for (int k = 0; k < row.size(); k++) { if (row.getQuick(k) != null && row.getQuick(k).equals(Boolean.TRUE)) { sum++; } } supportVector[i] = sum; } applet.combinationMap = this.combinationMap; applet.combinationMapReverse = this.combinationMapReverse; applet.matrix = this.matrix; applet.supportVector = supportVector; System.out.println("data loaded."); return null; } 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: private void impurlActionPerformed(java.awt.event.ActionEvent evt) { try { String prevurl = Prefs.getPref(PrefName.LASTIMPURL); String urlst = JOptionPane.showInputDialog(Resource.getResourceString("enturl"), prevurl); if (urlst == null || urlst.equals("")) return; Prefs.putPref(PrefName.LASTIMPURL, urlst); URL url = new URL(urlst); impURLCommon(urlst, url.openStream()); } catch (Exception e) { Errmsg.errmsg(e); } } Code Sample 2: 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); } } }
00
Code Sample 1: public T_Result unmarshall(URL url) throws SAXException, ParserConfigurationException, IOException { XMLReader parser = getParserFactory().newSAXParser().getXMLReader(); parser.setContentHandler(getContentHandler()); parser.setDTDHandler(getContentHandler()); parser.setEntityResolver(getContentHandler()); parser.setErrorHandler(getContentHandler()); InputSource inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); parser.parse(inputSource); return contentHandler.getRootObject(); } Code Sample 2: protected void registerClasses() throws PrintException { if (!init) { try { Enumeration<URL> somethingToRegister = this.getClass().getClassLoader().getResources("META-INF/" + getClass().getSimpleName() + ".properties"); while (somethingToRegister.hasMoreElements()) { URL url = (URL) somethingToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); try { Class cls = Class.forName(line); cls.newInstance(); log.debug("class " + line + " registered " + url); } catch (ClassNotFoundException e) { log.error("class " + line + " not found " + url, e); } catch (InstantiationException e) { log.error("class " + line + " not found " + url, e); } catch (IllegalAccessException e) { log.error("class " + line + " not found " + url, e); } line = buff.readLine(); } buff.close(); in.close(); } } catch (IOException e) { throw new PrintException(e.getMessage(), e); } init = true; } }
00
Code Sample 1: public InputStream resolve(String uri) throws SAJException { try { URI url = new URI(uri); InputStream stream = url.toURL().openStream(); if (stream == null) throw new SAJException("URI " + uri + " can't be resolved"); return stream; } catch (SAJException e) { throw e; } catch (Exception e) { throw new SAJException("Invalid uri to resolve " + uri, e); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } Code Sample 2: public void downloadTranslationsAndReload() { File languages = new File(this.translationsFile); try { URL languageURL = new URL(languageServer); InputStream is = languageURL.openStream(); OutputStream os = new FileOutputStream(languages); byte[] read = new byte[512000]; int bytesRead = 0; do { bytesRead = is.read(read); if (bytesRead > 0) { os.write(read, 0, bytesRead); } } while (bytesRead > 0); is.close(); os.close(); this.loadTranslations(); } catch (Exception e) { System.err.println("Remote languages file not found!"); if (languages.exists()) { try { XMLDecoder loader = new XMLDecoder(new FileInputStream(languages)); this.languages = (Hashtable) loader.readObject(); loader.close(); } catch (Exception ex) { ex.printStackTrace(); this.languages.put(naiveLanguage, new Hashtable()); } } else this.languages.put(naiveLanguage, new Hashtable()); } }
11
Code Sample 1: private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } Code Sample 2: private void show(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } }
00
Code Sample 1: public void uploadFile(ActionEvent event) throws IOException { InputFile inputFile = (InputFile) event.getSource(); synchronized (inputFile) { ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); String fileNewPath = arrangeUplodedFilePath(context.getRealPath(""), inputFile.getFile().getName()); File file = new File(fileNewPath); System.out.println(fileNewPath); DataInputStream inStream = new DataInputStream(new FileInputStream(inputFile.getFile())); DataOutputStream outStream = new DataOutputStream(new FileOutputStream(file)); int i = 0; byte[] buffer = new byte[512]; while ((i = inStream.read(buffer, 0, 512)) != -1) outStream.write(buffer, 0, i); } } Code Sample 2: private static boolean validateSshaPwd(String sSshaPwd, String sUserPwd) { boolean b = false; if (sSshaPwd != null && sUserPwd != null) { if (sSshaPwd.startsWith(SSHA_PREFIX)) { sSshaPwd = sSshaPwd.substring(SSHA_PREFIX.length()); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); md.update(sUserPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); b = MessageDigest.isEqual(hash, baPwdHash); } catch (Exception exc) { exc.printStackTrace(); } } } return b; }
00
Code Sample 1: public InputSource resolveEntity(String pPublicId, String pSystemId) throws SAXException, IOException { try { URL url = new URL(pSystemId); String fileName = (String) urlMap.get(url); if (fileName != null) { FileInputStream istream = new FileInputStream(new File(schemaDir, fileName)); InputSource isource = new InputSource(istream); isource.setSystemId(url.toString()); return isource; } String file = url.getFile(); if (file == null) { file = ""; } else { int offset = file.lastIndexOf('/'); if (offset >= 0) { file = file.substring(offset + 1); } } if ("".equals(file)) { file = "schema.xsd"; } int offset = file.lastIndexOf('.'); String prefix; String suffix; String numAsStr = ""; if (offset > 0 && offset < file.length()) { prefix = file.substring(0, offset); suffix = file.substring(offset); } else { prefix = file; suffix = ".xsd"; } File f; for (int num = 1; ; ++num) { f = new File(schemaDir, prefix + numAsStr + suffix); if (f.exists()) { numAsStr = "_" + num; } else { break; } } InputStream istream = url.openStream(); schemaDir.mkdirs(); FileOutputStream fos = new FileOutputStream(f); try { byte[] buffer = new byte[1024]; for (; ; ) { int res = istream.read(buffer); if (res == -1) { break; } else if (res > 0) { fos.write(buffer, 0, res); } } istream.close(); fos.close(); fos = null; } finally { if (fos != null) { try { f.delete(); } catch (Throwable ignore) { } } } urlMap.put(url, f.getName()); InputSource isource = new InputSource(new FileInputStream(f)); isource.setSystemId(url.toString()); return isource; } catch (Exception e) { JaxMeServlet.this.log("Failed to resolve URL " + pSystemId, e); } return null; } Code Sample 2: public void contextInitialized(ServletContextEvent event) { try { String osName = System.getProperty("os.name"); if (osName != null && osName.toLowerCase().contains("windows")) { URL url = new URL("http://localhost/"); URLConnection urlConn = url.openConnection(); urlConn.setDefaultUseCaches(false); } } catch (Throwable t) { } }
00
Code Sample 1: private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } } Code Sample 2: @Override public void exec() { BufferedReader in = null; try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer result = new StringBuffer(); String str; while ((str = in.readLine()) != null) { result.append(str); } logger.info("received message: " + result); } catch (Exception e) { logger.error("HttpGetEvent could not execute", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(128); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException 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(32); for (int j = 0; j < array.length; ++j) { int b = array[j] & TWO_BYTES; if (b < PAD_BELOW) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } } Code Sample 2: public byte[] pipeBytes() { byte ba[] = null; try { URL url = new URL(server); conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); ByteArrayOutputStream tout = new ByteArrayOutputStream(); int nmax = 10000; byte b[] = new byte[nmax + 1]; int nread = 0; while ((nread = is.read(b, 0, nmax)) >= 0) tout.write(b, 0, nread); ba = tout.toByteArray(); } catch (Exception ex) { System.err.println(ex); } return ba; }
00
Code Sample 1: private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); 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 static Object GET(String url, String[][] props) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); for (int i = 0; i < props.length; ++i) { conn.addRequestProperty(props[i][0], URLEncoder.encode(props[i][1], "UTF-8")); } conn.connect(); try { return conn.getContent(); } finally { conn.disconnect(); } }
11
Code Sample 1: @Test public void testCopy_inputStreamToWriter_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, "UTF8"); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } Code Sample 2: private boolean getCached(Get g) throws IOException { boolean ret = false; File f = getCachedFile(g); if (f.exists()) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(f); os = new FileOutputStream(getDestFile(g)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; }
11
Code Sample 1: private HashSet<String> href(String urlstr) throws IOException { HashSet<String> hrefs = new HashSet<String>(); URL url = new URL(urlstr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", "_session_id=" + _session_id); InputStreamReader r = new InputStreamReader(con.getInputStream()); StringWriter b = new StringWriter(); IOUtils.copyTo(r, b); r.close(); try { Thread.sleep(WAIT_SECONDS * 1000); } catch (Exception err) { } String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]"); for (String s1 : tokens) { if (!(s1.startsWith("a") && s1.contains("href"))) continue; String tokens2[] = s1.split("[\\\"\\\']"); for (String s2 : tokens2) { if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue; hrefs.add(s2); } } return hrefs; } Code Sample 2: void copyFile(File src, File dst) throws IOException { FileInputStream fis = new FileInputStream(src); byte[] buf = new byte[10000]; int n; FileOutputStream fos = new FileOutputStream(dst); while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); copied++; }
00
Code Sample 1: private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private Integer getInt(String sequence) throws NoSuchSequenceException { Connection conn = null; PreparedStatement read = null; PreparedStatement write = null; boolean success = false; try { conn = ds.getConnection(); conn.setTransactionIsolation(conn.TRANSACTION_REPEATABLE_READ); conn.setAutoCommit(false); read = conn.prepareStatement(SELECT_SQL); read.setString(1, sequence); ResultSet readRs = read.executeQuery(); if (!readRs.next()) { throw new NoSuchSequenceException(); } int currentSequenceId = readRs.getInt(1); int currentSequenceValue = readRs.getInt(2); Integer currentSequenceValueInteger = new Integer(currentSequenceValue); write = conn.prepareStatement(UPDATE_SQL); write.setInt(1, currentSequenceValue + 1); write.setInt(2, currentSequenceId); int rowsAffected = write.executeUpdate(); if (rowsAffected == 1) { success = true; return currentSequenceValueInteger; } else { logger.error("Something strange has happened. The row count was not 1, but was " + rowsAffected); return currentSequenceValueInteger; } } catch (SQLException sqle) { logger.error("Table based id generation failed : "); logger.error(sqle.getMessage()); return new Integer(0); } finally { if (read != null) { try { read.close(); } catch (Exception e) { } } if (write != null) { try { write.close(); } catch (Exception e) { } } if (conn != null) { try { if (success) { conn.commit(); } else { conn.rollback(); } conn.close(); } catch (Exception e) { } } } }
11
Code Sample 1: public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: protected void zipDirectory(File dir, File zipfile) throws IOException, IllegalArgumentException { if (!dir.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytes_read; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); } out.close(); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static Bitmap loadBitmap(String url) { try { final HttpClient httpClient = getHttpClient(); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inSampleSize = 1; return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; }
00
Code Sample 1: private String buildShaHashOf(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(source.getBytes()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } } Code Sample 2: static MenuListener openRecentHandler() { MenuListener handler = new MenuListener() { public void menuSelected(final MenuEvent event) { final JMenu menu = (JMenu) event.getSource(); menu.removeAll(); String[] recentURLSpecs = Application.getApp().getRecentURLSpecs(); for (int index = 0; index < recentURLSpecs.length; index++) { String urlSpec = recentURLSpecs[index]; JMenuItem menuItem = new JMenuItem(urlSpec); menu.add(menuItem); menuItem.setAction(openURLAction(urlSpec)); menuItem.setText(urlSpec); try { new java.net.URL(urlSpec).openStream(); } catch (java.io.IOException exception) { menuItem.setEnabled(false); } } menu.addSeparator(); final JMenuItem clearItem = new JMenuItem("Clear"); clearItem.setAction(new AbstractAction() { public void actionPerformed(final ActionEvent event) { Application.getApp().clearRecentItems(); } }); clearItem.setText("Clear"); menu.add(clearItem); } public void menuCanceled(final MenuEvent event) { } public void menuDeselected(final MenuEvent event) { } }; return handler; }
00
Code Sample 1: protected URL[][] getImageLinks(final URL url) { Lexer lexer; URL[][] ret; if (null != url) { try { lexer = new Lexer(url.openConnection()); ret = extractImageLinks(lexer, url); } catch (Throwable t) { System.out.println(t.getMessage()); ret = NONE; } } else ret = NONE; return (ret); } Code Sample 2: public File createWindow(String pdfUrl) { URL url; InputStream is; try { int fileLength = 0; String str; if (pdfUrl.startsWith("jar:/")) { str = "file.pdf"; is = this.getClass().getResourceAsStream(pdfUrl.substring(4)); } else { url = new URL(pdfUrl); is = url.openStream(); str = url.getPath().substring(url.getPath().lastIndexOf('/') + 1); fileLength = url.openConnection().getContentLength(); } final String filename = str; tempURLFile = File.createTempFile(filename.substring(0, filename.lastIndexOf('.')), filename.substring(filename.lastIndexOf('.')), new File(ObjectStore.temp_dir)); FileOutputStream fos = new FileOutputStream(tempURLFile); if (visible) { download.setLocation((coords.x - (download.getWidth() / 2)), (coords.y - (download.getHeight() / 2))); download.setVisible(true); } if (visible) { pb.setMinimum(0); pb.setMaximum(fileLength); String message = Messages.getMessage("PageLayoutViewMenu.DownloadWindowMessage"); message = message.replaceAll("FILENAME", filename); downloadFile.setText(message); Font f = turnOff.getFont(); turnOff.setFont(new Font(f.getName(), f.getStyle(), 8)); turnOff.setAlignmentY(JLabel.RIGHT_ALIGNMENT); turnOff.setText(Messages.getMessage("PageLayoutViewMenu.DownloadWindowTurnOff")); } byte[] buffer = new byte[4096]; int read; int current = 0; String rate = "kb"; int mod = 1000; if (fileLength > 1000000) { rate = "mb"; mod = 1000000; } if (visible) { progress = Messages.getMessage("PageLayoutViewMenu.DownloadWindowProgress"); if (fileLength < 1000000) progress = progress.replaceAll("DVALUE", (fileLength / mod) + " " + rate); else { String fraction = String.valueOf(((fileLength % mod) / 10000)); if (((fileLength % mod) / 10000) < 10) fraction = "0" + fraction; progress = progress.replaceAll("DVALUE", (fileLength / mod) + "." + fraction + " " + rate); } } while ((read = is.read(buffer)) != -1) { current = current + read; downloadCount = downloadCount + read; if (visible) { if (fileLength < 1000000) downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + " " + rate)); else { String fraction = String.valueOf(((current % mod) / 10000)); if (((current % mod) / 10000) < 10) fraction = "0" + fraction; downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + "." + fraction + " " + rate)); } pb.setValue(current); download.repaint(); } fos.write(buffer, 0, read); } fos.flush(); is.close(); fos.close(); if (visible) downloadMessage.setText("Download of " + filename + " is complete."); } catch (Exception e) { LogWriter.writeLog("[PDF] Exception " + e + " opening URL " + pdfUrl); e.printStackTrace(); } if (visible) download.setVisible(false); return tempURLFile; }
00
Code Sample 1: protected void find(final String pckgname, final boolean recursive) { URL url; String name = pckgname; name = name.replace('.', '/'); url = ResourceLocatorTool.getClassPathResource(ExampleRunner.class, name); File directory; try { directory = new File(URLDecoder.decode(url.getFile(), "UTF-8")); } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } if (directory.exists()) { logger.info("Searching for examples in \"" + directory.getPath() + "\"."); addAllFilesInDirectory(directory, pckgname, recursive); } else { try { logger.info("Searching for Demo classes in \"" + url + "\"."); final URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof JarURLConnection) { final JarURLConnection conn = (JarURLConnection) urlConnection; final JarFile jfile = conn.getJarFile(); final Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { final ZipEntry entry = e.nextElement(); final Class<?> result = load(entry.getName()); if (result != null) { addClassForPackage(result); } } } } catch (final IOException e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } catch (final Exception e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } } } Code Sample 2: public static void main(String[] args) { FTPClient client = new FTPClient(); try { File l_file = new File("C:/temp/testLoribel.html"); String l_url = "http://www.loribel.com/index.html"; GB_HttpTools.loadUrlToFile(l_url, l_file, ENCODING.ISO_8859_1); System.out.println("Try to connect..."); client.connect("ftp://ftp.phpnet.org"); System.out.println("Connected to server"); System.out.println("Try to connect..."); boolean b = client.login("fff", "ddd"); System.out.println("Login: " + b); String[] l_names = client.listNames(); GB_DebugTools.debugArray(GB_FtpDemo2.class, "names", l_names); b = client.makeDirectory("test02/toto"); System.out.println("Mkdir: " + b); String l_remote = "test02/test.xml"; InputStream l_local = new StringInputStream("Test111111111111111"); b = client.storeFile(l_remote, l_local); System.out.println("Copy file: " + b); } catch (Exception ex) { ex.printStackTrace(); } }
11
Code Sample 1: public static void request() { try { URL url = new URL("http://www.nseindia.com/marketinfo/companyinfo/companysearch.jsp?cons=ghcl&section=7"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public boolean optimize(int coreId) { try { URL url = new URL(solrUrl + "/core" + coreId + "/update"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Content-type", "text/xml"); conn.setRequestProperty("charset", "utf-8"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); System.out.println("******************optimizing"); wr.write("<optimize/>"); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: public void delete(int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt); if ((row < 1) || (row > max)) throw new IllegalArgumentException("Row number not between 1 and " + max); stmt.executeUpdate("delete from WordClassifications where Rank = " + row); for (int i = row; i < max; ++i) stmt.executeUpdate("update WordClassifications set Rank = " + i + " where Rank = " + (i + 1)); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public void init() { this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); try { if (memeId < 0) { } else { conurl = new URL(ServerURL + "?meme_id=" + memeId); java.io.InputStream xmlstr = conurl.openStream(); this.removeAllWorkSheets(); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT); this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE); this.setDupeStringMode(WorkBookHandle.SHAREDUPES); ExtenXLS.parseNBind(this, xmlstr); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); } } catch (Exception ex) { throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR); } }
00
Code Sample 1: public void deleteUser(String userID) throws XregistryException { try { userID = Utils.canonicalizeDN(userID); Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_USER_SQL_MAIN); statement1.setString(1, userID); statement1.executeUpdate(); PreparedStatement statement2 = connection.prepareStatement(DELETE_USER_SQL_DEPEND); statement2.setString(1, userID); statement2.executeUpdate(); connection.commit(); Collection<Group> groupList = groups.values(); for (Group group : groupList) { group.removeUser(userID); } log.info("Delete User " + userID); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } } Code Sample 2: public void retrieveChallenges(int num) throws MalformedURLException, IOException, FBErrorException, FBConnectionException { if (num < 1 || num > 100) { error = true; FBErrorException fbee = new FBErrorException(); fbee.setErrorCode(-100); fbee.setErrorText("Invalid GetChallenges range"); throw fbee; } URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Mode", "GetChallenges"); conn.setRequestProperty("X-FB-GetChallenges.Qty", new Integer(num).toString()); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { error = true; throw fbce; } catch (FBErrorException fbee) { error = true; throw fbee; } catch (Exception e) { error = true; FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("GetChallengesResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } NodeList challenge = fbresponse.getElementsByTagName("Challenge"); for (int i = 0; i < challenge.getLength(); i++) { NodeList children = challenge.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Text) { challenges.offer(children.item(j).getNodeValue()); } } } }
00
Code Sample 1: public boolean downloadFTP(String ipFTP, String loginFTP, String senhaFTP, String diretorioFTP, String diretorioAndroid, String arquivoFTP) throws SocketException, IOException { boolean retorno = false; FileOutputStream arqReceber = null; try { ftp.connect(ipFTP); Log.i("DownloadFTP", "Connected: " + ipFTP); ftp.login(loginFTP, senhaFTP); Log.i("DownloadFTP", "Logged on"); ftp.enterLocalPassiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); arqReceber = new FileOutputStream(file.toString()); ftp.retrieveFile("/tablet_ftp/Novo/socialAlimenta.xml", arqReceber); retorno = true; ftp.disconnect(); Log.i("DownloadFTP", "retorno:" + retorno); } catch (Exception e) { ftp.disconnect(); Log.e("DownloadFTP", "Erro:" + e.getMessage()); } finally { Log.e("DownloadFTP", "Finally"); } return retorno; } Code Sample 2: public void run() { OutputStream out = null; InputStream in = null; boolean success = false; String absoluteFileName = ""; try { String fileName = getFileName(softwareLocation); File downloadFolder = new File(Properties.downloadFolder); if (downloadFolder.exists()) { if (downloadFolder.isDirectory()) { fileName = downloadFolder.getPath() + File.separator + fileName; } } else { downloadFolder.mkdir(); fileName = downloadFolder.getPath() + File.separator + fileName; } File softwareFile = new File(fileName); absoluteFileName = softwareFile.getAbsolutePath(); if (softwareFile.exists() && softwareFile.length() == softwareSize) { XohmLogger.debugPrintln("Software file already exists. Exiting..."); listener.downloadComplete(true, softwareName, absoluteFileName); return; } else { try { File[] oldFiles = downloadFolder.listFiles(); for (int i = 0; i < oldFiles.length; i++) { oldFiles[i].delete(); } } catch (Exception ex) { } } File softwareTempFile = File.createTempFile("XOHMCM", null); URL url = new URL(softwareLocation); out = new BufferedOutputStream(new FileOutputStream(softwareTempFile)); URLConnection connection = url.openConnection(); in = connection.getInputStream(); listener.downloadStarted(softwareName); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; listener.downloadProgressNotification(softwareName, numWritten, softwareSize); } out.flush(); out.close(); in.close(); if (copyFile(softwareTempFile, softwareFile)) { XohmLogger.debugPrintln("Download complete: " + absoluteFileName + "\t" + numWritten); success = true; softwareTempFile.delete(); } } catch (Exception ex) { XohmLogger.warningPrintln("Software Update download failed - " + ex.getMessage(), null, null); ex.printStackTrace(); } listener.downloadComplete(success, softwareName, absoluteFileName); }
11
Code Sample 1: private void loadInitialDbState() throws IOException { InputStream in = SchemaAndDataPopulator.class.getClassLoader().getResourceAsStream(resourceName); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer); for (String statement : writer.toString().split(SQL_STATEMENT_DELIMITER)) { logger.info("Executing SQL Statement {}", statement); template.execute(statement); } } 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(); } }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: private boolean checkTimestamp(File timestamp, URL url) { try { if (timestamp.exists()) { FileReader reader = null; Date dateLocal = null; try { reader = new FileReader(timestamp); StringWriter tmp = new StringWriter(); IOUtils.copy(reader, tmp); dateLocal = this.FORMAT.parse(tmp.toString()); } catch (ParseException e) { timestamp.delete(); } catch (IOException e) { } finally { IOUtils.closeQuietly(reader); } if (dateLocal != null) { try { URLConnection conn = url.openConnection(); Date date = this.FORMAT.parse(this.FORMAT.format(new Date(conn.getLastModified()))); return (date.compareTo(dateLocal) == 0); } catch (IOException e) { } } } } catch (Throwable t) { } return false; }
00
Code Sample 1: private void javaToHtml(File source, File destination) throws IOException { Reader reader = new FileReader(source); Writer writer = new FileWriter(destination); JavaUtils.writeJava(reader, writer); writer.flush(); writer.close(); } Code Sample 2: private boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("hyk-proxy"); } catch (Exception e) { } return false; }
00
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: protected int authenticate(long companyId, String login, String password, String authType, Map headerMap, Map parameterMap) throws PortalException, SystemException { login = login.trim().toLowerCase(); long userId = GetterUtil.getLong(login); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { if (!Validator.isEmailAddress(login)) { throw new UserEmailAddressException(); } } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { if (Validator.isNull(login)) { throw new UserScreenNameException(); } } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { if (Validator.isNull(login)) { throw new UserIdException(); } } if (Validator.isNull(password)) { throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID); } int authResult = Authenticator.FAILURE; String[] authPipelinePre = PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_PRE); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = AuthPipeline.authenticateByEmailAddress(authPipelinePre, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = AuthPipeline.authenticateByScreenName(authPipelinePre, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = AuthPipeline.authenticateByUserId(authPipelinePre, companyId, userId, password, headerMap, parameterMap); } User user = null; try { if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { user = UserUtil.findByC_EA(companyId, login); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { user = UserUtil.findByC_SN(companyId, login); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { user = UserUtil.findByC_U(companyId, GetterUtil.getLong(login)); } } catch (NoSuchUserException nsue) { return Authenticator.DNE; } if (user.isDefaultUser()) { _log.error("The default user should never be allowed to authenticate"); return Authenticator.DNE; } if (!user.isPasswordEncrypted()) { user.setPassword(PwdEncryptor.encrypt(user.getPassword())); user.setPasswordEncrypted(true); UserUtil.update(user); } checkLockout(user); checkPasswordExpired(user); if (authResult == Authenticator.SUCCESS) { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK))) { String encPwd = PwdEncryptor.encrypt(password, user.getPassword()); if (user.getPassword().equals(encPwd)) { authResult = Authenticator.SUCCESS; } else if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.AUTH_MAC_ALLOW))) { try { MessageDigest digester = MessageDigest.getInstance(PropsUtil.get(PropsUtil.AUTH_MAC_ALGORITHM)); digester.update(login.getBytes("UTF8")); String shardKey = PropsUtil.get(PropsUtil.AUTH_MAC_SHARED_KEY); encPwd = Base64.encode(digester.digest(shardKey.getBytes("UTF8"))); if (password.equals(encPwd)) { authResult = Authenticator.SUCCESS; } else { authResult = Authenticator.FAILURE; } } catch (NoSuchAlgorithmException nsae) { throw new SystemException(nsae); } catch (UnsupportedEncodingException uee) { throw new SystemException(uee); } } else { authResult = Authenticator.FAILURE; } } } if (authResult == Authenticator.SUCCESS) { String[] authPipelinePost = PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_POST); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = AuthPipeline.authenticateByEmailAddress(authPipelinePost, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = AuthPipeline.authenticateByScreenName(authPipelinePost, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = AuthPipeline.authenticateByUserId(authPipelinePost, companyId, userId, password, headerMap, parameterMap); } } if (authResult == Authenticator.FAILURE) { try { String[] authFailure = PropsUtil.getArray(PropsUtil.AUTH_FAILURE); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { AuthPipeline.onFailureByEmailAddress(authFailure, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { AuthPipeline.onFailureByScreenName(authFailure, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { AuthPipeline.onFailureByUserId(authFailure, companyId, userId, headerMap, parameterMap); } if (!PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) { PasswordPolicy passwordPolicy = user.getPasswordPolicy(); int failedLoginAttempts = user.getFailedLoginAttempts(); int maxFailures = passwordPolicy.getMaxFailure(); if ((failedLoginAttempts >= maxFailures) && (maxFailures != 0)) { String[] authMaxFailures = PropsUtil.getArray(PropsUtil.AUTH_MAX_FAILURES); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { AuthPipeline.onMaxFailuresByEmailAddress(authMaxFailures, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { AuthPipeline.onMaxFailuresByScreenName(authMaxFailures, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { AuthPipeline.onMaxFailuresByUserId(authMaxFailures, companyId, userId, headerMap, parameterMap); } } } } catch (Exception e) { _log.error(e, e); } } return authResult; }
11
Code Sample 1: public static void copy(final File src, File dst, final boolean overwrite) throws IOException, IllegalArgumentException { if (!src.isFile() || !src.exists()) { throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); } if (dst.exists()) { if (dst.isDirectory()) { dst = new File(dst, src.getName()); } else if (dst.isFile()) { if (!overwrite) { throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); } } else { throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); } } final File dstParent = dst.getParentFile(); if (!dstParent.exists()) { if (!dstParent.mkdirs()) { throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); } } long fileSize = src.length(); if (fileSize > 20971520l) { final FileInputStream in = new FileInputStream(src); final FileOutputStream out = new FileOutputStream(dst); try { int doneCnt = -1; final int bufSize = 32768; final byte buf[] = new byte[bufSize]; while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) { if (doneCnt == 0) { Thread.yield(); } else { out.write(buf, 0, doneCnt); } } out.flush(); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } } } else { final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } } } } Code Sample 2: public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); }
11
Code Sample 1: public static List importSymbols(List symbols) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbols); IDQuoteFilter filter = new YahooIDQuoteFilter(); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; do { line = bufferedInput.readLine(); if (line != null) { try { IDQuote quote = filter.toIDQuote(line); quote.verify(); quotes.add(quote); } catch (QuoteFormatException e) { } } } while (line != null); bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; } Code Sample 2: public static List<String> getServers() throws Exception { List<String> servers = new ArrayList<String>(); URL url = new URL("http://tfast.org/en/servers.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.contains("serv=")) { int i = line.indexOf("serv="); servers.add(line.substring(i + 5, line.indexOf("\"", i))); } } in.close(); return servers; }
11
Code Sample 1: public XmldbURI createFile(String newName, InputStream is, Long length, String contentType) throws IOException, PermissionDeniedException, CollectionDoesNotExistException { if (LOG.isDebugEnabled()) LOG.debug("Create '" + newName + "' in '" + xmldbUri + "'"); XmldbURI newNameUri = XmldbURI.create(newName); MimeType mime = MimeTable.getInstance().getContentTypeFor(newName); if (mime == null) { mime = MimeType.BINARY_TYPE; } DBBroker broker = null; Collection collection = null; BufferedInputStream bis = new BufferedInputStream(is); VirtualTempFile vtf = new VirtualTempFile(); BufferedOutputStream bos = new BufferedOutputStream(vtf); IOUtils.copy(bis, bos); bis.close(); bos.close(); vtf.close(); if (mime.isXMLType() && vtf.length() == 0L) { if (LOG.isDebugEnabled()) LOG.debug("Creating dummy XML file for null resource lock '" + newNameUri + "'"); vtf = new VirtualTempFile(); IOUtils.write("<null_resource/>", vtf); vtf.close(); } TransactionManager transact = brokerPool.getTransactionManager(); Txn txn = transact.beginTransaction(); try { broker = brokerPool.get(subject); collection = broker.openCollection(xmldbUri, Lock.WRITE_LOCK); if (collection == null) { LOG.debug("Collection " + xmldbUri + " does not exist"); transact.abort(txn); throw new CollectionDoesNotExistException(xmldbUri + ""); } if (mime.isXMLType()) { if (LOG.isDebugEnabled()) LOG.debug("Inserting XML document '" + mime.getName() + "'"); VirtualTempFileInputSource vtfis = new VirtualTempFileInputSource(vtf); IndexInfo info = collection.validateXMLResource(txn, broker, newNameUri, vtfis); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(mime.getName()); collection.store(txn, broker, info, vtfis, false); } else { if (LOG.isDebugEnabled()) LOG.debug("Inserting BINARY document '" + mime.getName() + "'"); InputStream fis = vtf.getByteStream(); bis = new BufferedInputStream(fis); DocumentImpl doc = collection.addBinaryResource(txn, broker, newNameUri, bis, mime.getName(), length.longValue()); bis.close(); } transact.commit(txn); if (LOG.isDebugEnabled()) LOG.debug("Document created sucessfully"); } catch (EXistException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (TriggerException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (SAXException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (LockException e) { LOG.error(e); transact.abort(txn); throw new PermissionDeniedException(xmldbUri + ""); } catch (IOException e) { LOG.error(e); transact.abort(txn); throw e; } catch (PermissionDeniedException e) { LOG.error(e); transact.abort(txn); throw e; } finally { if (vtf != null) { vtf.delete(); } if (collection != null) { collection.release(Lock.WRITE_LOCK); } brokerPool.release(broker); if (LOG.isDebugEnabled()) LOG.debug("Finished creation"); } XmldbURI newResource = xmldbUri.append(newName); return newResource; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void adminUpdate(int i_id, double cost, String image, String thumbnail) { Connection con = null; try { tmpAdmin++; String name = "$tmp_admin" + tmpAdmin; con = getConnection(); PreparedStatement related1 = con.prepareStatement("CREATE TEMPORARY TABLE " + name + " TYPE=HEAP SELECT o_id FROM orders ORDER BY o_date DESC LIMIT 10000"); related1.executeUpdate(); related1.close(); PreparedStatement related2 = con.prepareStatement("SELECT ol2.ol_i_id, SUM(ol2.ol_qty) AS sum_ol FROM order_line ol, order_line ol2, " + name + " t " + "WHERE ol.ol_o_id = t.o_id AND ol.ol_i_id = ? AND ol2.ol_o_id = t.o_id AND ol2.ol_i_id <> ? " + "GROUP BY ol2.ol_i_id ORDER BY sum_ol DESC LIMIT 0,5"); related2.setInt(1, i_id); related2.setInt(2, i_id); ResultSet rs = related2.executeQuery(); int[] related_items = new int[5]; int counter = 0; int last = 0; while (rs.next()) { last = rs.getInt(1); related_items[counter] = last; counter++; } for (int i = counter; i < 5; i++) { last++; related_items[i] = last; } rs.close(); related2.close(); PreparedStatement related3 = con.prepareStatement("DROP TABLE " + name); related3.executeUpdate(); related3.close(); PreparedStatement statement = con.prepareStatement("UPDATE item SET i_cost = ?, i_image = ?, i_thumbnail = ?, i_pub_date = CURRENT_DATE(), " + " i_related1 = ?, i_related2 = ?, i_related3 = ?, i_related4 = ?, i_related5 = ? WHERE i_id = ?"); statement.setDouble(1, cost); statement.setString(2, image); statement.setString(3, thumbnail); statement.setInt(4, related_items[0]); statement.setInt(5, related_items[1]); statement.setInt(6, related_items[2]); statement.setInt(7, related_items[3]); statement.setInt(8, related_items[4]); statement.setInt(9, i_id); statement.executeUpdate(); con.commit(); statement.close(); returnConnection(con); } catch (java.lang.Exception ex) { try { con.rollback(); ex.printStackTrace(); } catch (Exception se) { System.err.println("Transaction rollback failed."); } } } Code Sample 2: public static JSONArray getFriends(long[] uids) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(FRIENDS_URI); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("uids", arrayToString(uids, ","))); post.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONArray(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
11
Code Sample 1: private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); InputStream is = vds.getContentStream(); IOUtils.copy(is, m_zout); is.close(); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } } Code Sample 2: public void performOk(final IProject project, final TomcatPropertyPage page) { page.setPropertyValue("tomcat.jdbc.driver", c_drivers.getText()); page.setPropertyValue("tomcat.jdbc.url", url.getText()); page.setPropertyValue("tomcat.jdbc.user", username.getText()); page.setPropertyValue("tomcat.jdbc.password", password.getText()); File lib = new File(page.tomcatHome.getText(), "lib"); if (!lib.exists()) { lib = new File(new File(page.tomcatHome.getText(), "common"), "lib"); if (!lib.exists()) { Logger.log(Logger.ERROR, "Not properly location of Tomcat Home at :: " + lib); throw new IllegalStateException("Not properly location of Tomcat Home"); } } final File conf = new File(page.tomcatHome.getText(), "conf/Catalina/localhost"); if (!conf.exists()) { final boolean create = NexOpenUIActivator.getDefault().getTomcatConfProperty(); if (create) { if (Logger.getLog().isDebugEnabled()) { Logger.getLog().debug("Create directory " + conf); } try { conf.mkdirs(); } catch (final SecurityException se) { Logger.getLog().error("Retrieved a Security exception creating " + conf, se); Logger.log(Logger.ERROR, "Not created " + conf + " directory. Not enough privilegies. Message :: " + se.getMessage()); } } } String str_driverLibrary = LIBRARIES.get(c_drivers.getText()); if ("<mysql_driver>".equals(str_driverLibrary)) { str_driverLibrary = NexOpenUIActivator.getDefault().getMySQLDriver(); } final File driverLibrary = new File(lib, str_driverLibrary); if (!driverLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + str_driverLibrary)); fos = new FileOutputStream(driverLibrary); IOUtils.copy(driver, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the driver jar file to Tomcat", e); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } page.processTomcatCfg(c_drivers.getText(), url.getText(), username.getText(), password.getText()); }
00
Code Sample 1: public static String encodeMD5(String value) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); BASE64Encoder encoder = new BASE64Encoder(); md.update(value.getBytes()); byte[] raw = md.digest(); result = encoder.encode(raw); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } Code Sample 2: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public void processDeleteHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (holdingBean.getId() == null) throw new IllegalArgumentException("holdingId is null"); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); String sql = "delete from WM_LIST_HOLDING " + "where ID_HOLDING=? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(2, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: @Override protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient f = new FTPSClient(); f.connect(fpi.getHost()); f.login(fpi.getUsername(), fpi.getPassword()); return f; }
00
Code Sample 1: private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); } Code Sample 2: public PropertiesImpl(URL url) { this(); InputStream in = null; lock.lock(); try { in = url.openStream(); PropertiesLexer lexer = new PropertiesLexer(in); lexer.lex(); List<PropertiesToken> list = lexer.getList(); new PropertiesParser(list, this).parse(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { } lock.unlock(); } }
11
Code Sample 1: @Override protected void doFetch(HttpServletRequest request, HttpServletResponse response) throws IOException, GadgetException { if (request.getHeader("If-Modified-Since") != null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } String host = request.getHeader("Host"); if (!lockedDomainService.isSafeForOpenProxy(host)) { String msg = "Embed request for url " + getParameter(request, URL_PARAM, "") + " made to wrong domain " + host; logger.info(msg); throw new GadgetException(GadgetException.Code.INVALID_PARAMETER, msg); } HttpRequest rcr = buildHttpRequest(request, URL_PARAM); HttpResponse results = requestPipeline.execute(rcr); if (results.isError()) { HttpRequest fallbackRcr = buildHttpRequest(request, FALLBACK_URL_PARAM); if (fallbackRcr != null) { results = requestPipeline.execute(fallbackRcr); } } if (contentRewriterRegistry != null) { try { results = contentRewriterRegistry.rewriteHttpResponse(rcr, results); } catch (RewritingException e) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e); } } for (Map.Entry<String, String> entry : results.getHeaders().entries()) { String name = entry.getKey(); if (!DISALLOWED_RESPONSE_HEADERS.contains(name.toLowerCase())) { response.addHeader(name, entry.getValue()); } } String responseType = results.getHeader("Content-Type"); if (!StringUtils.isEmpty(rcr.getRewriteMimeType())) { String requiredType = rcr.getRewriteMimeType(); if (requiredType.endsWith("/*") && !StringUtils.isEmpty(responseType)) { requiredType = requiredType.substring(0, requiredType.length() - 2); if (!responseType.toLowerCase().startsWith(requiredType.toLowerCase())) { response.setContentType(requiredType); responseType = requiredType; } } else { response.setContentType(requiredType); responseType = requiredType; } } setResponseHeaders(request, response, results); if (results.getHttpStatusCode() != HttpResponse.SC_OK) { response.sendError(results.getHttpStatusCode()); } IOUtils.copy(results.getResponse(), response.getOutputStream()); } Code Sample 2: public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); }
11
Code Sample 1: public void readEntry(String name, InputStream input) throws Exception { File file = new File(this.directory, name); OutputStream output = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { org.apache.commons.io.IOUtils.copy(input, output); } finally { output.close(); } } Code Sample 2: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }