label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; } Code Sample 2: public static void copyFile(final File source, final File target) throws FileNotFoundException, IOException { FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } out.close(); in.close(); }
11
Code Sample 1: @Override public void loadData() { try { String url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=11&f=2099&g=d&ignore=.csv"; URLConnection conn = (new URL(url)).openConnection(); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); String str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double open = Double.parseDouble(split[1]); final double high = Double.parseDouble(split[2]); final double low = Double.parseDouble(split[3]); final double close = Double.parseDouble(split[4]); final int volume = Integer.parseInt(split[5]); final double adjClose = Double.parseDouble(split[6]); final HistoricalPrice price = new HistoricalPrice(date, open, high, low, close, volume, adjClose); historicalPrices.add(price); } in.close(); url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=17&f=2008&g=v&ignore=.csv"; conn = (new URL(url)).openConnection(); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double amount = Double.parseDouble(split[1]); final Dividend dividend = new Dividend(date, amount); dividends.add(dividend); } in.close(); } catch (final IOException ioe) { logger.error("Error parsing historical prices for " + getSymbol(), ioe); } } Code Sample 2: private MimeTypes() { try { final URL url = RES.getURL("types"); final InputStream is = url.openStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); while (line != null) { line = line.trim(); final int p = line.indexOf('#'); if (p >= 0) { line = line.substring(0, p).trim(); } if (line.length() > 0) { final StringTokenizer st = new StringTokenizer(line, " \t"); if (st.countTokens() > 1) { final String mime = st.nextToken(); while (st.hasMoreTokens()) { extnMap.put(st.nextToken(), mime); } } } line = br.readLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } canParse.add(TEXT_HTML); canParse.add(TEXT_CSS); }
00
Code Sample 1: public void lookupAllFactories() throws IOException { Enumeration setOfFactories = null; ClassLoader classLoader = null; InputStream inputStream = null; classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } return cl; } }); if (classLoader == null) { return; } try { setOfFactories = classLoader.getResources("META-INF/services/javax.print.StreamPrintServiceFactory"); } catch (IOException e) { e.printStackTrace(); throw new IOException("IOException during resource finding"); } try { while (setOfFactories.hasMoreElements()) { URL url = (URL) setOfFactories.nextElement(); inputStream = url.openStream(); getFactoryClasses(inputStream); } } catch (IOException e1) { e1.printStackTrace(); throw new IOException("IOException during resource reading"); } } Code Sample 2: @Override public synchronized File download_dictionary(Dictionary dict, String localfpath) { abort = false; try { URL dictionary_location = new URL(dict.getLocation()); InputStream in = dictionary_location.openStream(); FileOutputStream w = new FileOutputStream(local_cache, false); int b = 0; while ((b = in.read()) != -1) { w.write(b); if (abort) throw new Exception("Download Aborted"); } in.close(); w.close(); File lf = new File(localfpath); FileInputStream r = new FileInputStream(local_cache); FileOutputStream fw = new FileOutputStream(lf); int c; while ((c = r.read()) != -1) fw.write(c); r.close(); fw.close(); clearCache(); return lf; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidTupleOperationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } clearCache(); return null; }
00
Code Sample 1: public static byte[] ComputeForBinary(String ThisString) throws Exception { byte[] Result; MessageDigest MD5Hasher; MD5Hasher = MessageDigest.getInstance("MD5"); MD5Hasher.update(ThisString.getBytes("iso-8859-1")); Result = MD5Hasher.digest(); return Result; } Code Sample 2: public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } }
11
Code Sample 1: public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); } Code Sample 2: public void testDigest() { try { String myinfo = "我的测试信息"; MessageDigest alga = MessageDigest.getInstance("SHA-1"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); System.out.println("本信息摘要是:" + byte2hex(digesta)); MessageDigest algb = MessageDigest.getInstance("SHA-1"); algb.update(myinfo.getBytes()); if (MessageDigest.isEqual(digesta, algb.digest())) { System.out.println("信息检查正常"); } else { System.out.println("摘要不相同"); } } catch (NoSuchAlgorithmException ex) { System.out.println("非法摘要算法"); } }
00
Code Sample 1: public void delete(int id) 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 WebServices where WebServiceId = " + id); stmt.executeUpdate("delete from WebServiceParams where WebServiceId = " + id); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException { if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src)); if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src)); if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst)); if (dst.exists()) { dst.delete(); if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst)); } boolean hasId3v1 = new MyID3v1().hasID3v1(src); long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0; long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src); long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1); OutputStream os = null; InputStream is = null; try { dst.getParentFile().mkdirs(); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag); is = new FileInputStream(src); is = new BufferedInputStream(is); is.skip(id3v2HeadLength); long total_to_read = src.length(); total_to_read -= id3v1Length; total_to_read -= id3v2HeadLength; total_to_read -= id3v2TailLength; byte buffer[] = new byte[1024]; long total_read = 0; while (total_read < total_to_read) { int remainder = (int) (total_to_read - total_read); int readSize = Math.min(buffer.length, remainder); int read = is.read(buffer, 0, readSize); if (read <= 0) throw new IOException("unexpected EOF"); os.write(buffer, 0, read); total_read += read; } if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag); if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag); } finally { try { if (is != null) is.close(); } catch (Throwable e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (Throwable e) { Debug.debug(e); } } } Code Sample 2: public final void build() { if (!built_) { built_ = true; final boolean[] done = new boolean[] { false }; Runnable runnable = new Runnable() { public void run() { try { exists_ = true; URL url = getContentURL(); URLConnection cnx = url.openConnection(); cnx.connect(); lastModified_ = cnx.getLastModified(); length_ = cnx.getContentLength(); type_ = cnx.getContentType(); if (isDirectory()) { InputStream in = cnx.getInputStream(); BufferedReader nr = new BufferedReader(new InputStreamReader(in)); FuVectorString v = readList(nr); nr.close(); v.sort(); v.uniq(); list_ = v.toArray(); } } catch (Exception ex) { exists_ = false; } done[0] = true; } }; Thread t = new Thread(runnable, "VfsFileUrl connection " + getContentURL()); t.setPriority(Math.max(Thread.MIN_PRIORITY, t.getPriority() - 1)); t.start(); for (int i = 0; i < 100; i++) { if (done[0]) break; try { Thread.sleep(300L); } catch (InterruptedException ex) { } } if (!done[0]) { t.interrupt(); exists_ = false; canRead_ = false; FuLog.warning("VFS: fail to get " + url_); } } }
00
Code Sample 1: public void patchFile(final File classFile) { if (!classFile.exists()) { myErrors.add(new FormErrorInfo(null, "Class to bind does not exist: " + myRootContainer.getClassToBind())); return; } FileInputStream fis; try { byte[] patchedData; fis = new FileInputStream(classFile); try { patchedData = patchClass(fis); if (patchedData == null) { return; } } finally { fis.close(); } FileOutputStream fos = new FileOutputStream(classFile); try { fos.write(patchedData); } finally { fos.close(); } } catch (IOException e) { myErrors.add(new FormErrorInfo(null, "Cannot read or write class file " + classFile.getPath() + ": " + e.toString())); } } 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); }
11
Code Sample 1: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: public void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new ProjectEditPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } } Code Sample 2: private static void copyFile(File sourceFile, File destFile) { try { 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(); } } } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: private void googleImageSearch() { bottomShowing = true; googleSearched = true; googleImageLocation = 0; googleImages = new Vector<String>(); custom = ""; int r = JOptionPane.showConfirmDialog(this, "Customize google search?", "Google Search", JOptionPane.YES_NO_OPTION); if (r == JOptionPane.YES_OPTION) { custom = JOptionPane.showInputDialog("Custom Search", ""); } else { custom = artist; } try { String u = "http://images.google.com/images?q=" + custom; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String lin = new String(); while ((lin = readIn.readLine()) != null) { while (lin.contains("href=\"/imgres?imgurl=")) { while (!lin.contains(">")) { lin += readIn.readLine(); } String s = lin.substring(lin.indexOf("href=\"/imgres?imgurl="), lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); lin = lin.substring(lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); if (s.contains("&amp;") && s.indexOf("http://") < s.indexOf("&amp;")) { s = s.substring(s.indexOf("http://"), s.indexOf("&amp;")); } else { s = s.substring(s.indexOf("http://"), s.length()); } googleImages.add(s); } } readIn.close(); } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton1.setEnabled(false); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); } Code Sample 2: private synchronized File gzipTempFile(File tempFile) throws BlogunityException { try { File gzippedFile = new File(BlogunityManager.getSystemConfiguration().getTempDir(), tempFile.getName() + ".gz"); GZIPOutputStream zos = new GZIPOutputStream(new FileOutputStream(gzippedFile)); byte[] readBuffer = new byte[2156]; int bytesIn = 0; FileInputStream fis = new FileInputStream(tempFile); while ((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } fis.close(); zos.close(); return gzippedFile; } catch (Exception e) { throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.FEED_GZIP_FAILED, e)); } }
00
Code Sample 1: public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static void BubbleSortLong1(long[] num) { boolean flag = true; // set flag to true to begin first pass long temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } }
00
Code Sample 1: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); } Code Sample 2: public static URLConnection getURLConnection(URL url, boolean ignoreBadCertificates) throws KeyManagementException, NoSuchAlgorithmException, UnknownHostException, IOException { SSLSocketFactory sslSocketFactory = null; if (ignoreBadCertificates) { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, getAllTrustingTrustManager(), new java.security.SecureRandom()); sslSocketFactory = sslContext.getSocketFactory(); } else { sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); return url.openConnection(); }
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 static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
11
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 boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static byte[] SHA1(String... strings) { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.reset(); for (String string : strings) { digest.update(string.getBytes("UTF-8")); } return digest.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.toString(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString(), e); } } Code Sample 2: private static List<InputMethodDescriptor> loadIMDescriptors() { String nm = SERVICES + InputMethodDescriptor.class.getName(); Enumeration<URL> en; LinkedList<InputMethodDescriptor> imdList = new LinkedList<InputMethodDescriptor>(); NativeIM nativeIM = ContextStorage.getNativeIM(); imdList.add(nativeIM); try { en = ClassLoader.getSystemResources(nm); ClassLoader cl = ClassLoader.getSystemClassLoader(); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStreamReader isr = new InputStreamReader(url.openStream(), "UTF-8"); BufferedReader br = new BufferedReader(isr); String str = br.readLine(); while (str != null) { str = str.trim(); int comPos = str.indexOf("#"); if (comPos >= 0) { str = str.substring(0, comPos); } if (str.length() > 0) { imdList.add((InputMethodDescriptor) cl.loadClass(str).newInstance()); } str = br.readLine(); } } } catch (Exception e) { } return imdList; }
00
Code Sample 1: public ResponseStatus submit(Collection<SubmissionData> data) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); if (data.size() > 50) throw new IllegalArgumentException("Max 50 submissions at once"); StringBuilder builder = new StringBuilder(data.size() * 100); int index = 0; for (SubmissionData submissionData : data) { builder.append(submissionData.toString(sessionId, index)); builder.append('\n'); index++; } String body = builder.toString(); if (Caller.getInstance().isDebugMode()) System.out.println("submit: " + body); HttpURLConnection urlConnection = Caller.getInstance().openConnection(submissionUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); int statusCode = ResponseStatus.codeForStatus(status); if (statusCode == ResponseStatus.FAILED) { return new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1)); } return new ResponseStatus(statusCode); } Code Sample 2: @Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } }
11
Code Sample 1: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } } Code Sample 2: public void copyFile(File source, File destination, boolean lazy) { if (!source.exists()) { return; } if (lazy) { String oldContent = null; try { oldContent = read(source); } catch (Exception e) { return; } String newContent = null; try { newContent = read(destination); } catch (Exception e) { } if ((oldContent == null) || !oldContent.equals(newContent)) { copyFile(source, destination, false); } } else { if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { _log.error(ioe.getMessage()); } } }
00
Code Sample 1: private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } } Code Sample 2: public static String getMD5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); String salt = "UseTheForce4"; password = salt + password; md5.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, md5.digest()).toString(16); } catch (Exception e) { } return password; }
11
Code Sample 1: public boolean authenticate(String plaintext) throws NoSuchAlgorithmException { String[] passwordParts = this.password.split("\\$"); md = MessageDigest.getInstance("SHA-1"); md.update(passwordParts[1].getBytes()); isAuthenticated = toHex(md.digest(plaintext.getBytes())).equalsIgnoreCase(passwordParts[2]); return isAuthenticated; } Code Sample 2: public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public 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; }
00
Code Sample 1: private void copyFile(String path) { try { File srcfile = new File(srcdir, path); File destfile = new File(destdir, path); File parent = destfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); int bytes_read = 0; byte buffer[] = new byte[512]; while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } fis.close(); fos.close(); } catch (IOException e) { throw new BuildException("Error while copying file " + path); } } Code Sample 2: public String md5(String string) throws GeneralSecurityException { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(string.getBytes()); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); }
00
Code Sample 1: public void deleteSingle(String tbName, String idFld, String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (tbName == null || tbName.length() == 0 || id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delSQL = "delete from " + tbName + " where " + idFld + "='" + id + "'"; con.setAutoCommit(false); prepStmt = con.prepareStatement(delSQL); prepStmt.executeUpdate(); con.commit(); prepStmt.close(); con.close(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } } Code Sample 2: public boolean doUpload(int count) { String objFileName = Long.toString(new java.util.Date().getTime()) + Integer.toString(count); try { this.objectFileName[count] = objFileName + "_bak." + this.sourceFileExt[count]; File objFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); if (objFile.exists()) { this.doUpload(count); } else { objFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(objFile); BufferedOutputStream bos = new BufferedOutputStream(fos); int readLength = 0; int offset = 0; String str = ""; long readSize = 0L; while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) { str = new String(this.b, 0, readLength); if (str.indexOf("Content-Type:") != -1) { break; } } this.inStream.readLine(this.b, 0, this.b.length); while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) { str = new String(this.b, 0, readLength); if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45 && this.b[3] == 45 && this.b[4] == 45) { break; } bos.write(this.b, 0, readLength); readSize += readLength; if (readSize > this.size) { this.fileMessage[count] = "�ϴ��ļ������ļ���С�������ƣ�"; this.ok = false; break; } } if (this.ok) { bos.flush(); bos.close(); int fileLength = (int) (objFile.length()); byte[] bb = new byte[fileLength - 2]; FileInputStream fis = new FileInputStream(objFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(bb, 0, (fileLength - 2)); fis.close(); bis.close(); this.objectFileName[count] = objFileName + "." + this.sourceFileExt[count]; File ok_file = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); ok_file.createNewFile(); BufferedOutputStream bos_ok = new BufferedOutputStream(new FileOutputStream(ok_file)); bos_ok.write(bb); bos_ok.close(); objFile.delete(); this.fileMessage[count] = "OK"; return true; } else { bos.flush(); bos.close(); File delFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); delFile.delete(); this.objectFileName[count] = "none"; return false; } } catch (Exception e) { this.objectFileName[count] = "none"; this.fileMessage[count] = e.toString(); return false; } }
11
Code Sample 1: public void testQueryForBinary() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + "images/photo.png"); assertNotNull(source); assertEquals(false, source.exists()); OutputStream os = source.getOutputStream(); assertNotNull(os); String content = "foo is a bar"; os.write(content.getBytes()); os.flush(); os.close(); QueryResultSource qResult = (QueryResultSource) resolveSource(BASE_URL + "images?/*[contains(local-name(), 'photo.png')]"); assertNotNull(qResult); Collection results = qResult.getChildren(); assertEquals(1, results.size()); Iterator it = results.iterator(); JCRNodeSource rSrc = (JCRNodeSource) it.next(); InputStream rSrcIn = rSrc.getInputStream(); ByteArrayOutputStream actualOut = new ByteArrayOutputStream(); IOUtils.copy(rSrcIn, actualOut); rSrcIn.close(); assertEquals(content, actualOut.toString()); actualOut.close(); rSrc.delete(); } Code Sample 2: 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: @Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; } Code Sample 2: public void sendRequest(String method) { try { url = new URL(urlStr); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod(method); httpURLConnection.setDoOutput(true); httpURLConnection.getOutputStream().flush(); httpURLConnection.getOutputStream().close(); System.out.println(httpURLConnection.getResponseMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: @Override protected ActionForward executeAction(ActionMapping mapping, ActionForm form, User user, HttpServletRequest request, HttpServletResponse response) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); String attributeIdentifier = request.getParameter("identifier"); if (resourceId != 0L && StringUtils.hasText(attributeIdentifier)) { try { BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, attributeIdentifier, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; } catch (DataRetrievalFailureException e) { addGlobalError(request, "errors.notFound"); } catch (Exception e) { addGlobalError(request, e); } } return mapping.getInputForward(); }
11
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
00
Code Sample 1: protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); } Code Sample 2: @Override public URLConnection openConnection(URL url, Proxy proxy) throws IOException { if (null == url) { throw new IllegalArgumentException(Messages.getString("luni.1B")); } String host = url.getHost(); if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) { return new FileURLConnection(url); } URL ftpURL = new URL("ftp", host, url.getFile()); return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy); }
11
Code Sample 1: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } } Code Sample 2: public void 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: private void sort() { for (int i = 0; i < density.length; i++) { for (int j = density.length - 2; j >= i; j--) { if (density[j] > density[j + 1]) { KDNode n = nonEmptyNodesArray[j]; nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1]; nonEmptyNodesArray[j + 1] = n; double d = density[j]; density[j] = density[j + 1]; density[j + 1] = d; } } } } Code Sample 2: public static String login() throws Exception { if (sid == null) { String login = ROLAPClientAux.loadProperties().getProperty("user"); String password = ROLAPClientAux.loadProperties().getProperty("password"); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); String password2 = asHexString(md.digest()); String query = "/server/login?user=" + login + "&extern_password=" + password + "&password=" + password2; Vector<String> res = ROLAPClientAux.sendRequest(query); String vals[] = res.get(0).split(";"); sid = vals[0]; } return sid; }
11
Code Sample 1: public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); } Code Sample 2: protected void copy(File source, File destination) throws IOException { final FileChannel inChannel = new FileInputStream(source).getChannel(); final FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: protected static String encodePassword(String raw_password) throws DatabaseException { String clean_password = validatePassword(raw_password); try { MessageDigest md = MessageDigest.getInstance(DEFAULT_PASSWORD_DIGEST); md.update(clean_password.getBytes(DEFAULT_PASSWORD_ENCODING)); String digest = new String(Base64.encodeBase64(md.digest())); if (log.isDebugEnabled()) log.debug("encodePassword: digest=" + digest); return digest; } catch (UnsupportedEncodingException e) { throw new DatabaseException("encoding-problem with password", e); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("digest-problem encoding password", e); } } Code Sample 2: public int update(BusinessObject o) throws DAOException { int update = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_CURRENCY")); pst.setString(1, curr.getName()); pst.setInt(2, curr.getIdBase()); pst.setDouble(3, curr.getValue()); pst.setInt(4, curr.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; }
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 InputStream download_file(String sessionid, String key) { InputStream is = null; String urlString = "https://s2.cloud.cm/rpc/raw?c=Storage&m=download_file&key=" + key; try { String apple = ""; URL url = new URL(urlString); Log.d("current running function name:", "download_file"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", "PHPSESSID=" + sessionid); conn.setRequestMethod("POST"); conn.setDoInput(true); is = conn.getInputStream(); return is; } catch (Exception e) { e.printStackTrace(); Log.d("download problem", "download problem"); } return is; }
00
Code Sample 1: public URLConnection getResourceConnection(String name) throws ResourceException { if (context == null) throw new ResourceException("There is no ServletContext to get the requested resource"); URL url = null; try { url = context.getResource("/WEB-INF/scriptags/" + name); return url.openConnection(); } catch (Exception e) { throw new ResourceException(String.format("Resource '%s' could not be found (url: %s)", name, url), e); } } Code Sample 2: @Override public AC3DModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); AC3DModel model = loadModel(url.openStream(), skin); if (baseURLWasNull) { popBaseURL(); } return (model); }
00
Code Sample 1: public void bubble() { boolean test = false; int kars = 0, tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } System.out.print(kars + " " + tas); } 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 int process(ProcessorContext context) throws InterruptedException, ProcessorException { logger.info("JAISaveTask:process"); final RenderedOp im = (RenderedOp) context.get("RenderedOp"); final String path = "s3://s3.amazonaws.com/rssfetch/" + (new Guid()); final PNGEncodeParam.RGB encPar = new PNGEncodeParam.RGB(); encPar.setTransparentRGB(new int[] { 0, 0, 0 }); File tmpFile = null; try { tmpFile = File.createTempFile("thmb", ".png"); OutputStream out = new FileOutputStream(tmpFile); final ParameterBlock pb = (new ParameterBlock()).addSource(im).add(out).add("png").add(encPar); JAI.create("encode", pb, null); out.flush(); out.close(); FileInputStream in = new FileInputStream(tmpFile); final XFile xfile = new XFile(path); final XFileOutputStream xout = new XFileOutputStream(xfile); final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfile.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType("image/png"); xfa.setContentLength(tmpFile.length()); } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); context.put("outputPath", path); } catch (IOException e) { logger.error(e); throw new ProcessorException(e); } catch (Throwable e) { logger.error(e); throw new ProcessorException(e); } finally { if (tmpFile != null && tmpFile.exists()) { tmpFile.delete(); } } return TaskState.STATE_MO_START + TaskState.STATE_ENCODE; } Code Sample 2: private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) throws IOException { boolean resultat = false; FileInputStream fis = new FileInputStream(sRC2); FileOutputStream fos = new FileOutputStream(dEST2); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); progressEnCours.setValue(0); progressEnCours.setString(sRC2 + " : 0 %"); channelSrc.transferTo(0, channelSrc.size(), channelDest); progressEnCours.setValue(100); progressEnCours.setString(sRC2 + " : 100 %"); if (channelSrc.size() == channelDest.size()) { resultat = true; } else { resultat = false; } fis.close(); fos.close(); return (resultat); }
00
Code Sample 1: private String getMd5(String base64image) { String token = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(base64image.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); token = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return token; } Code Sample 2: @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(); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: JSONResponse execute() throws ServerException, RtmApiException, IOException { HttpClient httpclient = new DefaultHttpClient(); URI uri; try { uri = new URI(this.request.getUrl()); HttpPost httppost = new HttpPost(uri); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(is))); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } return new JSONResponse(sb.toString()); } finally { is.close(); } } catch (URISyntaxException e) { throw new RtmApiException(e.getMessage()); } catch (ClientProtocolException e) { throw new RtmApiException(e.getMessage()); } }
00
Code Sample 1: public Vector _getSiteNames() { Vector _mySites = new Vector(); boolean gotSites = false; while (!gotSites) { try { URL dataurl = new URL(getDocumentBase(), siteFile); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String S = readme.readLine(); if (S == null) break; StringTokenizer st = new StringTokenizer(S); _mySites.addElement(st.nextToken()); } gotSites = true; } catch (IOException e) { _mySites.removeAllElements(); gotSites = false; } } return (_mySites); } Code Sample 2: public Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } }
11
Code Sample 1: public static void copy(String from, String to) throws Exception { File inputFile = new File(from); File outputFile = new File(to); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } Code Sample 2: @Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (beforeServingFile(req, resp)) { String pathInfo = req.getPathInfo(); Validate.notNull(pathInfo, "the path info is null -> the sevlet should be mapped with /<mapping>/*"); String resurouce = pathInfo.substring(1); if (log.isDebugEnabled()) { log.debug("resource to expose: " + resurouce); } String extension = resurouce.substring(resurouce.lastIndexOf('.') + 1); MimeType mimeType = MimeTypeRegistry.getByExtension(extension); Validate.notNull(mimeType, "no mimetype found for extension: " + extension); if (log.isDebugEnabled()) { log.debug("the mime type to set: " + mimeType.getMimeType()); } File f = new File(mappedFolder, resurouce); Validate.isTrue(f.exists(), "file: " + f + " does not exist"); Validate.isTrue(f.canRead(), "can not read the file: " + f); if (log.isDebugEnabled()) { log.debug("exposing the file: " + f); } resp.setContentType(mimeType.getMimeType()); FileInputStream fis = new FileInputStream(f); ServletOutputStream os = resp.getOutputStream(); IOUtils.copy(fis, os); os.flush(); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(os); } }
11
Code Sample 1: public boolean save(String trxName) { if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) { StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause); int no = DB.executeUpdate(sql.toString(), trxName); log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value); if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql); return true; } StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause); boolean success = true; if (DB.isRemoteObjects()) { log.fine("[" + trxName + "] - Remote - " + m_value); Server server = CConnection.get().getServer(); try { if (server != null) { success = server.updateLOB(sql.toString(), m_displayType, m_value, trxName, SecurityToken.getInstance()); if (CLogMgt.isLevelFinest()) log.fine("server.updateLOB => " + success); return success; } log.log(Level.SEVERE, "AppsServer not found"); } catch (RemoteException ex) { log.log(Level.SEVERE, "AppsServer error", ex); } return false; } log.fine("[" + trxName + "] - Local - " + m_value); Trx trx = null; if (trxName != null) trx = Trx.get(trxName, false); Connection con = null; if (trx != null) con = trx.getConnection(); if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); if (con == null) { log.log(Level.SEVERE, "Could not get Connection"); return false; } PreparedStatement pstmt = null; success = true; try { pstmt = con.prepareStatement(sql.toString()); if (m_displayType == DisplayType.TextLong) pstmt.setString(1, (String) m_value); else pstmt.setBytes(1, (byte[]) m_value); int no = pstmt.executeUpdate(); if (no != 1) { log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql); success = false; } } catch (Throwable e) { log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e); success = false; } finally { DB.close(pstmt); pstmt = null; } if (success) { if (trx != null) { trx = null; con = null; } else { try { con.commit(); } catch (Exception e) { log.log(Level.SEVERE, "[" + trxName + "] - commit ", e); success = false; } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } if (!success) { log.severe("[" + trxName + "] - rollback"); if (trx != null) { trx.rollback(); trx = null; con = null; } else { try { con.rollback(); } catch (Exception ee) { log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee); } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } return success; } Code Sample 2: @Override public boolean setupDatabaseSchema() { Configuration cfg = Configuration.getInstance(); Connection con = getConnection(); if (null == con) return false; try { String sql = FileTool.readFile(cfg.getProperty("database.sql.rootdir") + System.getProperty("file.separator") + cfg.getProperty("database.sql.mysql.setupschema")); sql = sql.replaceAll(MYSQL_SQL_SCHEMA_REPLACEMENT, StateSaver.getInstance().getDatabaseSettings().getSchema()); con.setAutoCommit(false); Statement stmt = con.createStatement(); String[] sqlParts = sql.split(";"); for (String sqlPart : sqlParts) { if (sqlPart.trim().length() > 0) stmt.executeUpdate(sqlPart); } con.commit(); JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionsuccess"), language.getProperty("dialog.information.title"), JOptionPane.INFORMATION_MESSAGE); return true; } catch (SQLException e) { Logger.logException(e); } try { if (con != null) con.rollback(); } catch (SQLException e) { Logger.logException(e); } JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionerror"), language.getProperty("dialog.error.title"), JOptionPane.ERROR_MESSAGE); return false; }
11
Code Sample 1: public static void testclass(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.emptyClass(ClassWriter.ACC_PUBLIC, "TestClass", "java/lang/Object"); MethodInfo newMethod = writer.addMethod(ClassWriter.ACC_PUBLIC | ClassWriter.ACC_STATIC, "main", "([Ljava/lang/String;)V"); CodeAttribute attribute = newMethod.getCodeAttribute(); int constantIndex = writer.getStringConstantIndex("It's alive! It's alive!!"); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int methodRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); ArrayList instructions = new ArrayList(); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); operands = new byte[1]; operands[0] = (byte) constantIndex; instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("ldc"), 0, operands, false)); operands = new byte[2]; NetByte.intToPair(methodRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("return"), 0, null, false)); attribute.insertInstructions(0, 0, instructions); attribute.setMaxLocals(1); attribute.codeCheck(); System.out.println("constantIndex=" + constantIndex + " fieldRef=" + fieldRefIndex + " methodRef=" + methodRefIndex); writer.writeClass(new FileOutputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); writer.readClass(new FileInputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: public static int copyFile(File src, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(src).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } return 1; }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new RuntimeException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
00
Code Sample 1: private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); } Code Sample 2: @Override @RemoteMethod public boolean encrypt(int idAnexo) { try { Anexo anexo = anexoService.selectById(idAnexo); aes.init(Cipher.ENCRYPT_MODE, aeskeySpec); FileInputStream fis = new FileInputStream(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho()); CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(config.baseDir + "/arquivos_upload_direto/encrypt/" + anexo.getAnexoCaminho()), aes); IOUtils.copy(fis, cos); cos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.seriesstatementpanel.getEnteredvalues().get(0).toString().trim().equals("")) { this.showWarningMessage("Enter Series Title"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveSeriesName("2", seriesstatementpanel.getEnteredvalues(), patlib); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SeriesNameServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } } Code Sample 2: private TupleQueryResult evaluate(String location, String query, QueryLanguage queryLn) throws Exception { location += "?query=" + URLEncoder.encode(query, "UTF-8") + "&queryLn=" + queryLn.getName(); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Accept", TupleQueryResultFormat.SPARQL.getDefaultMIMEType()); conn.connect(); try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return QueryResultIO.parse(conn.getInputStream(), TupleQueryResultFormat.SPARQL); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
00
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: public boolean download(String address, String localFileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } return true; } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return false; }
00
Code Sample 1: public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public LocationResponse getResponse(LocationRequest lrq) throws UnregisteredComponentException { LocationResponse lrs = lrq.createResponse(); try { String rqs, rss; rqs = encodeSkyhookRequest(lrq); if (null == rqs) { lrs.setError("No authentication was provided."); return lrs; } URL url = new URL(this.skyhookServerUri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "text/xml"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(rqs); wr.flush(); BufferedReader rd; rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); rss = ""; String line; while ((line = rd.readLine()) != null) rss += line; rd.close(); decodeSkyhookResponse(rss, lrs); } catch (Exception e) { e.printStackTrace(); lrs.setError("Error querying Skyhook"); } return lrs; }
11
Code Sample 1: private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public SM2Client(String umn, String authorizationID, String protocol, String serverName, Map props, CallbackHandler handler) { super(SM2_MECHANISM + "-" + umn, authorizationID, protocol, serverName, props, handler); this.umn = umn; complete = false; state = 0; if (sha == null) try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException x) { cat.error("SM2Client()", x); throw new RuntimeException(String.valueOf(x)); } sha.update(String.valueOf(umn).getBytes()); sha.update(String.valueOf(authorizationID).getBytes()); sha.update(String.valueOf(protocol).getBytes()); sha.update(String.valueOf(serverName).getBytes()); sha.update(String.valueOf(properties).getBytes()); sha.update(String.valueOf(Thread.currentThread().getName()).getBytes()); uid = new BigInteger(1, sha.digest()).toString(26); Ec = null; }
11
Code Sample 1: @Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } } Code Sample 2: protected void setupService(MessageContext msgContext) throws Exception { String realpath = msgContext.getStrProp(Constants.MC_REALPATH); String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION); if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION; if ((realpath != null) && (realpath.endsWith(extension))) { String jwsFile = realpath; String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); File f2 = new File(jwsFile); if (!f2.exists()) { throw new FileNotFoundException(rel); } if (rel.charAt(0) == '/') { rel = rel.substring(1); } int lastSlash = rel.lastIndexOf('/'); String dir = null; if (lastSlash > 0) { dir = rel.substring(0, lastSlash); } String file = rel.substring(lastSlash + 1); String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR); if (outdir == null) outdir = "."; if (dir != null) { outdir = outdir + File.separator + dir; } File outDirectory = new File(outdir); if (!outDirectory.exists()) { outDirectory.mkdirs(); } if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile); String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "java"; String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "class"; if (log.isDebugEnabled()) { log.debug("jFile: " + jFile); log.debug("cFile: " + cFile); log.debug("outdir: " + outdir); } File f1 = new File(cFile); String clsName = null; if (clsName == null) clsName = f2.getName(); if (clsName != null && clsName.charAt(0) == '/') clsName = clsName.substring(1); clsName = clsName.substring(0, clsName.length() - extension.length()); clsName = clsName.replace('/', '.'); if (log.isDebugEnabled()) log.debug("ClsName: " + clsName); if (!f1.exists() || f2.lastModified() > f1.lastModified()) { log.debug(Messages.getMessage("compiling00", jwsFile)); log.debug(Messages.getMessage("copy00", jwsFile, jFile)); FileReader fr = new FileReader(jwsFile); FileWriter fw = new FileWriter(jFile); char[] buf = new char[4096]; int rc; while ((rc = fr.read(buf, 0, 4095)) >= 0) fw.write(buf, 0, rc); fw.close(); fr.close(); log.debug("javac " + jFile); Compiler compiler = CompilerFactory.getCompiler(); compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext)); compiler.setDestination(outdir); compiler.addFile(jFile); boolean result = compiler.compile(); (new File(jFile)).delete(); if (!result) { (new File(cFile)).delete(); Document doc = XMLUtils.newDocument(); Element root = doc.createElementNS("", "Errors"); StringBuffer message = new StringBuffer("Error compiling "); message.append(jFile); message.append(":\n"); List errors = compiler.getErrors(); int count = errors.size(); for (int i = 0; i < count; i++) { CompilerError error = (CompilerError) errors.get(i); if (i > 0) message.append("\n"); message.append("Line "); message.append(error.getStartLine()); message.append(", column "); message.append(error.getStartColumn()); message.append(": "); message.append(error.getMessage()); } root.appendChild(doc.createTextNode(message.toString())); throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root }); } ClassUtils.removeClassLoader(clsName); soapServices.remove(clsName); } ClassLoader cl = ClassUtils.getClassLoader(clsName); if (cl == null) { cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile); } msgContext.setClassLoader(cl); SOAPService rpc = (SOAPService) soapServices.get(clsName); if (rpc == null) { rpc = new SOAPService(new RPCProvider()); rpc.setName(clsName); rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName); rpc.setEngine(msgContext.getAxisEngine()); String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS); if (allowed == null) allowed = "*"; rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed); String scope = (String) getOption(RPCProvider.OPTION_SCOPE); if (scope == null) scope = Scope.DEFAULT.getName(); rpc.setOption(RPCProvider.OPTION_SCOPE, scope); rpc.getInitializedServiceDesc(msgContext); soapServices.put(clsName, rpc); } rpc.setEngine(msgContext.getAxisEngine()); rpc.init(); msgContext.setService(rpc); } if (log.isDebugEnabled()) { log.debug("Exit: JWSHandler::invoke"); } }
11
Code Sample 1: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } } Code Sample 2: 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 String get(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent:", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += '\n' + s; } return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } Code Sample 2: public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; }
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: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; 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 < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
00
Code Sample 1: public void execute(File sourceFile, File destinationFile, Properties htmlCleanerConfig) { FileReader reader = null; Writer writer = null; try { reader = new FileReader(sourceFile); logger.info("Using source file: " + trimPath(userDir, sourceFile)); if (!destinationFile.getParentFile().exists()) { createDirectory(destinationFile.getParentFile()); } writer = new FileWriter(destinationFile); logger.info("Destination file: " + trimPath(userDir, destinationFile)); execute(reader, writer, htmlCleanerConfig); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); writer = null; } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public static boolean update(Departamento objDepartamento) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update departamento set nome = ?, sala = ?, telefone = ?, id_orgao = ? where id_departamento= ?"; pst = c.prepareStatement(sql); pst.setString(1, objDepartamento.getNome()); pst.setString(2, objDepartamento.getSala()); pst.setString(3, objDepartamento.getTelefone()); pst.setLong(4, (objDepartamento.getOrgao()).getCodigo()); pst.setInt(5, objDepartamento.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
00
Code Sample 1: private InputStream loadSource(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); } Code Sample 2: private void addLine(AmazonItem coverAdress) { try { URL url = new URL("" + coverAdress.getMediumImageURL()); TableItem ligne1 = new TableItem(table, SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_MNEMONIC); url.openConnection(); InputStream is = url.openStream(); Image coverPicture = new Image(display, is); coverAvailable.add(url); ligne1.setImage(new Image[] { coverPicture, null }); ligne1.setText(new String[] { null, coverAdress.getArtist() + "\n" + coverAdress.getCDTitle() + "\nTrack : " + coverAdress.getNbTrack() }); } catch (MalformedURLException e) { } catch (IOException e) { System.err.println(e.toString()); } }
11
Code Sample 1: public static void copy(File sourceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: public JSONObject getSourceGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph src = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { src = manager.getSourceGraph(); if (src != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(src); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No source graph loaded."); } } catch (Exception e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Cannot load source graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); } Code Sample 2: public static void saveFile(final URL url, final File file) throws IOException { final InputStream in = url.openStream(); final FileOutputStream out = new FileOutputStream(file); byte[] data = new byte[8 * 1024]; int length; while ((length = in.read(data)) != -1) { out.write(data, 0, length); } in.close(); out.close(); }
00
Code Sample 1: public static final InputStream openStream(Bundle bundle, IPath file, boolean localized) throws IOException { URL url = null; if (!localized) { url = findInPlugin(bundle, file); if (url == null) url = findInFragments(bundle, file); } else { url = FindSupport.find(bundle, file); } if (url != null) return url.openStream(); throw new IOException("Cannot find " + file.toString()); } Code Sample 2: private void executeRequest(OperationContext context) throws java.lang.Throwable { long t1 = System.currentTimeMillis(); DirectoryParams params = context.getRequestOptions().getDirectoryOptions(); try { String srvCfg = context.getRequestContext().getApplicationConfiguration().getCatalogConfiguration().getParameters().getValue("openls.directory"); HashMap<String, String> poiProperties = params.getPoiProperties(); Set<String> keys = poiProperties.keySet(); Iterator<String> iter = keys.iterator(); StringBuffer filter = new StringBuffer(); while (iter.hasNext()) { String key = iter.next(); QueryFilter queryFilter = new QueryFilter(key, poiProperties.get(key)); filter.append(makePOIRequest(queryFilter)); } String sUrl = srvCfg + "/query?" + filter.toString(); LOGGER.info("REQUEST=\n" + sUrl); URL url = new URL(sUrl); URLConnection conn = url.openConnection(); String line = ""; String sResponse = ""; InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader rd = new BufferedReader(isr); while ((line = rd.readLine()) != null) { sResponse += line; } rd.close(); url = null; parsePOIResponse(sResponse, params); } catch (Exception p_e) { LOGGER.severe("Throwing exception" + p_e.getMessage()); throw p_e; } finally { long t2 = System.currentTimeMillis(); LOGGER.info("PERFORMANCE: " + (t2 - t1) + " ms spent performing service"); } }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } } Code Sample 2: @Action(value = "ajaxFileUploads", results = { }) public void ajaxFileUploads() throws IOException { String extName = ""; String newFilename = ""; String nowTimeStr = ""; String realpath = ""; if (Validate.StrNotNull(this.getImgdirpath())) { realpath = "Uploads/" + this.getImgdirpath() + "/"; } else { realpath = this.isexistdir(); } SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath(""); savePath = savePath + realpath; HttpServletResponse response = ServletActionContext.getResponse(); int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000; sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); nowTimeStr = sDateFormat.format(new Date()); String filename = request.getHeader("X-File-Name"); if (filename.lastIndexOf(".") >= 0) { extName = filename.substring(filename.lastIndexOf(".")); } newFilename = nowTimeStr + rannum + extName; PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage()); } try { is = request.getInputStream(); fos = new FileOutputStream(new File(savePath + newFilename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success:'" + realpath + newFilename + "'}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { this.setImgdirpath(null); fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
11
Code Sample 1: private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private File uploadFile(InputStream inputStream, File file) { FileOutputStream fileOutputStream = null; try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileUtils.touch(file); fileOutputStream = new FileOutputStream(file); IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new FileOperationException("Failed to save uploaded image", e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { LOGGER.warn("Failed to close resources on uploaded file", e); } } return file; } Code Sample 2: 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 :("); } }
11
Code Sample 1: public static void copyFile(File srcFile, File dstFile) { logger.info("Create file : " + dstFile.getPath()); try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel dstChannel = new FileOutputStream(dstFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } }
00
Code Sample 1: public static String getDigestResponse(String user, String password, String method, String requri, String authstr) { String realm = ""; String nonce = ""; String opaque = ""; String algorithm = ""; String qop = ""; StringBuffer digest = new StringBuffer(); String cnonce; String noncecount; String pAuthStr = authstr; int ptr = 0; String response = ""; int i = 0; StringTokenizer st = new StringTokenizer(pAuthStr, ","); StringTokenizer stprob = null; String str = null; String key = null; String value = null; Properties probs = new Properties(); while (st.hasMoreTokens()) { String nextToken = st.nextToken(); stprob = new StringTokenizer(nextToken, "="); key = stprob.nextToken(); value = stprob.nextToken(); if (value.charAt(0) == '"' || value.charAt(0) == '\'') { value = value.substring(1, value.length() - 1); } probs.put(key, value); } digest.append("Digest username=\"" + user + "\", "); digest.append("realm=\""); digest.append(probs.getProperty("realm")); digest.append("\", "); digest.append("nonce=\""); digest.append(probs.getProperty("nonce")); digest.append("\", "); digest.append("uri=\"" + requri + "\", "); cnonce = "abcdefghi"; noncecount = "00000001"; String toDigest = user + ":" + realm + ":" + password; byte[] digestbuffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toDigest.getBytes()); digestbuffer = md.digest(); } catch (Exception e) { System.err.println("Error creating digest request: " + e); return null; } digest.append("qop=\"auth\", "); digest.append("cnonce=\"" + cnonce + "\", "); digest.append("nc=" + noncecount + ", "); digest.append("response=\"" + response + "\""); if (probs.getProperty("opaque") != null) { digest.append(", opaque=\"" + probs.getProperty("opaque") + "\""); } System.out.println("SipProtocol: Digest calculated."); return digest.toString(); } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
11
Code Sample 1: public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } } Code Sample 2: public static final void copy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
11
Code Sample 1: public static void main(String[] args) throws ParseException, FileNotFoundException, IOException { InputStream input = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); Translator t = new Translator(input, "UTF8"); Node template = Translator.Start(); File langs = new File("support/support/translate/languages"); for (File f : langs.listFiles()) { if (f.getName().endsWith(".lng")) { input = new BufferedInputStream(new FileInputStream(f)); try { Translator.ReInit(input, "UTF8"); } catch (java.lang.NullPointerException e) { new Translator(input, "UTF8"); } Node newFile = Translator.Start(); ArrayList<Addition> additions = new ArrayList<Addition>(); syncKeys(template, newFile, additions); ArrayList<String> fileLines = new ArrayList<String>(); Scanner scanner = new Scanner(new BufferedReader(new FileReader(f))); while (scanner.hasNextLine()) { fileLines.add(scanner.nextLine()); } int offset = 0; for (Addition a : additions) { System.out.println("Key added " + a + " to " + f.getName()); if (a.afterLine < 0 || a.afterLine >= fileLines.size()) { fileLines.add(a.getAddition(0)); } else { fileLines.add(a.afterLine + (offset++) + 1, a.getAddition(0)); } } f.delete(); Writer writer = new BufferedWriter(new FileWriter(f)); for (String s : fileLines) writer.write(s + "\n"); writer.close(); System.out.println("Language " + f.getName() + " had " + additions.size() + " additions"); } } File defFile = new File(langs, "language.lng"); defFile.delete(); defFile.createNewFile(); InputStream copyStream = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); OutputStream out = new BufferedOutputStream(new FileOutputStream(defFile)); int c = 0; while ((c = copyStream.read()) >= 0) out.write(c); out.close(); System.out.println("Languages updated."); } Code Sample 2: private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); } Code Sample 2: public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } }
11
Code Sample 1: private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; } Code Sample 2: public void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } }
11
Code Sample 1: private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void main(String[] args) throws Exception { String localSrc = args[0]; String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(dst), conf); OutputStream out = fs.create(new Path(dst), new Progressable() { public void progress() { System.out.print("."); } }); IOUtils.copyBytes(in, out, 4096, true); }
00
Code Sample 1: InputStream selectSource(String item) { if (item == null) { item = "http://pushnpop.net:8912/subpop.ogg"; } if (item.endsWith(".pls")) { item = fetch_pls(item); if (item == null) { return null; } } else if (item.endsWith(".m3u")) { item = fetch_m3u(item); if (item == null) { return null; } } if (!item.endsWith(".ogg")) { return null; } InputStream is = null; URLConnection urlc = null; try { URL url = null; if (running_as_applet) { url = new URL(getCodeBase(), item); } else { url = new URL(item); } urlc = url.openConnection(); is = urlc.getInputStream(); current_source = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getFile(); } catch (Exception ee) { System.err.println(ee); } if (is == null && !running_as_applet) { try { is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + item); current_source = null; } catch (Exception ee) { System.err.println(ee); } } if (is == null) { return null; } System.out.println("Select: " + item); { boolean find = false; for (int i = 0; i < cb.getItemCount(); i++) { String foo = (String) (cb.getItemAt(i)); if (item.equals(foo)) { find = true; break; } } if (!find) { cb.addItem(item); } } int i = 0; String s = null; String t = null; udp_port = -1; udp_baddress = null; while (urlc != null && true) { s = urlc.getHeaderField(i); t = urlc.getHeaderFieldKey(i); if (s == null) { break; } i++; if (t != null && t.equals("udp-port")) { try { udp_port = Integer.parseInt(s); } catch (Exception ee) { System.err.println(ee); } } else if (t != null && t.equals("udp-broadcast-address")) { udp_baddress = s; } } return is; } Code Sample 2: private void onDhReply(final SshDhReply msg) throws GeneralSecurityException, IOException { if ((this.keyPair == null) || this.connection.isServer()) throw new SshException("%s: unexpected %s", this.connection.uri, msg.getType()); final BigInteger k; { final DHPublicKeySpec remoteKeySpec = new DHPublicKeySpec(new BigInteger(msg.f), P1, G); final KeyFactory dhKeyFact = KeyFactory.getInstance("DH"); final DHPublicKey remotePubKey = (DHPublicKey) dhKeyFact.generatePublic(remoteKeySpec); final KeyAgreement dhKex = KeyAgreement.getInstance("DH"); dhKex.init(this.keyPair.getPrivate()); dhKex.doPhase(remotePubKey, true); k = new BigInteger(dhKex.generateSecret()); } final MessageDigest md = createMessageDigest(); final byte[] h; { updateByteArray(md, SshVersion.LOCAL.toString().getBytes()); updateByteArray(md, this.connection.getRemoteSshVersion().toString().getBytes()); updateByteArray(md, this.keyExchangeInitLocal.getPayload()); updateByteArray(md, this.keyExchangeInitRemote.getPayload()); updateByteArray(md, msg.hostKey); updateByteArray(md, ((DHPublicKey) this.keyPair.getPublic()).getY().toByteArray()); updateByteArray(md, msg.f); updateBigInt(md, k); h = md.digest(); } if (this.sessionId == null) this.sessionId = h; this.keyExchangeInitLocal = null; this.keyExchangeInitRemote = null; this.h = h; this.k = k; this.connection.send(new SshKeyExchangeNewKeys()); }
11
Code Sample 1: private void copyFile(File s, File d) throws IOException { d.getParentFile().mkdirs(); FileChannel inChannel = new FileInputStream(s).getChannel(); FileChannel outChannel = new FileOutputStream(d).getChannel(); int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } inChannel.close(); outChannel.close(); d.setLastModified(s.lastModified()); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; } Code Sample 2: public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); return bytesToHexString(md.digest()); }
00
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { log.error(e, e); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public String preProcessHTML(String uri) { final StringBuffer buf = new StringBuffer(); try { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { buf.append(data); buf.append('\n'); } }; } }; URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); new ParserDelegator().parse(rd, doc.getReader(0), Boolean.TRUE); } catch (MalformedURLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } return buf.toString(); }
11
Code Sample 1: public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: public void writeTo(OutputStream out) throws IOException, MessagingException { InputStream in = getInputStream(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(in, base64Out); base64Out.close(); mFile.delete(); } Code Sample 2: public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } }
00
Code Sample 1: protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
00
Code Sample 1: private void loadProperties() throws IOException { if (properties == null) { return; } printDebugIfEnabled("Loading properties"); InputStream inputStream = configurationSource.openStream(); Properties newProperties = new Properties(); try { newProperties.load(inputStream); } finally { inputStream.close(); } String importList = newProperties.getProperty(KEY_IMPORT); if (importList != null) { importList = importList.trim(); if (importList.length() > 0) { String[] filesToImport = importList.split(","); if (filesToImport != null && filesToImport.length != 0) { String configurationContext = configurationSource.toExternalForm(); int lastSlash = configurationContext.lastIndexOf('/'); lastSlash += 1; configurationContext = configurationContext.substring(0, lastSlash); for (int i = 0; i < filesToImport.length; i++) { String filenameToImport = filesToImport[i]; URL urlToImport = new URL(configurationContext + filenameToImport); InputStream importStream = null; try { printDebugIfEnabled("Importing file", urlToImport); importStream = urlToImport.openStream(); newProperties.load(importStream); } catch (IOException e) { printError("Error importing properties file: " + filenameToImport + "(" + urlToImport + ")", e, true); } finally { if (importStream != null) importStream.close(); } } } } } if (devDebug) { Set properties = newProperties.entrySet(); printDebugIfEnabled("_____ Properties List START _____"); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); printDebugIfEnabled((String) entry.getKey(), entry.getValue()); } printDebugIfEnabled("______ Properties List END ______"); } properties.clear(); properties.putAll(newProperties); } Code Sample 2: public void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("fff", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(reqEntity); NULogger.getLogger().info("Now uploading your file into 2shared.com. Please wait......................"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); status = UploadStatus.GETTINGLINK; HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String page = EntityUtils.toString(resEntity); NULogger.getLogger().log(Level.INFO, "PAGE :{0}", page); } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); 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(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public boolean check(Object credentials) { try { byte[] digest = null; if (credentials instanceof Password || credentials instanceof String) { synchronized (__TYPE) { if (__md == null) __md = MessageDigest.getInstance("MD5"); __md.reset(); __md.update(credentials.toString().getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } if (digest == null || digest.length != _digest.length) return false; for (int i = 0; i < digest.length; i++) if (digest[i] != _digest[i]) return false; return true; } else if (credentials instanceof MD5) { MD5 md5 = (MD5) credentials; if (_digest.length != md5._digest.length) return false; for (int i = 0; i < _digest.length; i++) if (_digest[i] != md5._digest[i]) return false; return true; } else if (credentials instanceof Credential) { return ((Credential) credentials).check(this); } else { log.warn("Can't check " + credentials.getClass() + " against MD5"); return false; } } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); return false; } }
11
Code Sample 1: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); } Code Sample 2: public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } }
00
Code Sample 1: public static void writeToPetrify(TransitionSystem ts, Writer bw) throws IOException { File temp = new File("_temp"); BufferedWriter tw = new BufferedWriter(new FileWriter(temp)); BufferedReader tr = new BufferedReader(new FileReader(temp)); HashSet<ModelGraphVertex> sources = new HashSet<ModelGraphVertex>(); HashSet<ModelGraphVertex> dests = new HashSet<ModelGraphVertex>(); ArrayList transitions = ts.getEdges(); HashSet<String> events = new HashSet<String>(); for (int i = 0; i < transitions.size(); i++) { TransitionSystemEdge transition = (TransitionSystemEdge) transitions.get(i); events.add(replaceBadSymbols(transition.getIdentifier())); sources.add(transition.getSource()); dests.add(transition.getDest()); if (ts.getStateNameFlag() == TransitionSystem.ID) { tw.write("s" + transition.getSource().getId() + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write("s" + transition.getDest().getId() + "\n"); } else { tw.write(replaceBadSymbols(transition.getSource().getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getDest().getIdentifier()) + "\n"); } } tw.close(); bw.write(".model " + ts.getName().replaceAll(" ", "_") + "\n"); bw.write(".dummy "); Iterator it = events.iterator(); while (it.hasNext()) bw.write(it.next() + " "); bw.write("\n"); bw.write(".state graph" + "\n"); int c; while ((c = tr.read()) != -1) bw.write(c); tr.close(); temp.delete(); for (ModelGraphVertex dest : dests) { if (sources.contains(dest)) { sources.remove(dest); } } ModelGraphVertex source = sources.isEmpty() ? null : sources.iterator().next(); if (ts.getStateNameFlag() == TransitionSystem.ID) { if (!ts.hasExplicitEnd()) bw.write(".marking {s0}" + "\n"); else bw.write(".marking {s" + source.getId() + "}\n"); } else if (source != null) { bw.write(".marking {" + replaceBadSymbols(source.getIdentifier()) + "}\n"); } bw.write(".end"); } Code Sample 2: public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
00
Code Sample 1: private void loadOperatorsXML() { startwindow.setMessage("Loading Operators..."); try { URL url = Application.class.getClassLoader().getResource(Resources.getString("OPERATORS_XML")); InputStream input = url.openStream(); OperatorsReader.registerOperators(Resources.getString("OPERATORS_XML"), input); } catch (FileNotFoundException e) { Logger.logException("File '" + Resources.getString("OPERATORS_XML") + "' not found.", e); } catch (IOException error) { Logger.logException(error.getMessage(), error); } } Code Sample 2: public static byte[] encrypt(String x) throws Exception { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); return d.digest(); }
11
Code Sample 1: public void render(final HttpServletRequest request, final HttpServletResponse response, final byte[] bytes, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } response.setContentLength(bytes.length); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); } Code Sample 2: private static void exportConfigResource(ClassLoader classLoader, String resourceName, String targetFileName) throws Exception { InputStream is = classLoader.getResourceAsStream(resourceName); FileOutputStream fos = new FileOutputStream(targetFileName, false); IOUtils.copy(is, fos); fos.close(); is.close(); }
00
Code Sample 1: public static Vector webService(String siteUrl, String login, String password, String table, String station, String element, String dayFrom, String dayTo, String filePath) throws Exception { Service service = new Service(); Call call = (Call) service.createCall(); if (login != null) { call.setUsername(login); if (password != null) { call.setPassword(password); } System.err.println("Info: authentication user=" + login + " passwd=" + password + " at " + siteUrl); } call.setTargetEndpointAddress(new URL(siteUrl)); call.setOperationName("syncData"); Vector exportList = (Vector) call.invoke(new Object[] { table, station, element, dayFrom, dayTo }); if (exportList != null) { for (int k = 0; k < exportList.size(); k++) { HashMap exportDescr = (HashMap) exportList.get(k); String url = (String) exportDescr.get("fileName"); log.debug("result URL is " + url); String fileName = null; URL dataurl = new URL(url); String filePart = dataurl.getFile(); if (filePart == null) { throw new Exception("Error: file part in the data URL is null"); } else { fileName = filePart.substring(filePart.lastIndexOf("/") < 0 ? 0 : filePart.lastIndexOf("/") + 1); if (filePath != null) { fileName = filePath + fileName; } log.debug("local file name is " + fileName); } FileOutputStream fos = new FileOutputStream(fileName); if (fos == null) { throw new Exception("Error: file output stream is null"); } InputStream strm = dataurl.openStream(); if (strm == null) { throw new Exception("Error: data input stream is null"); } else { int c; while ((c = strm.read()) != -1) { fos.write(c); } } strm.close(); fos.close(); File file = new File(fileName); exportDescr.put("fileName", file.getCanonicalPath()); } } return exportList; } Code Sample 2: public WordEntry[] getVariants(String word) throws MatchPackException { String upperWord = word.toUpperCase(); if (variantsDictionary == null) { try { long start = System.currentTimeMillis(); URL url = this.getClass().getResource("varlex.dic"); ObjectInputStream si = new ObjectInputStream(url.openStream()); variantsDictionary = (Map) si.readObject(); long end = System.currentTimeMillis(); System.out.println("loaded " + (end - start) + "ms"); si.close(); } catch (Exception e) { throw new MatchPackException("cannot load: varlex.dic " + e.getMessage()); } } List l = (List) variantsDictionary.get(upperWord); if (l == null) { return new WordEntry[0]; } return (WordEntry[]) l.toArray(new WordEntry[0]); }
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 { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
00
Code Sample 1: private String send(String method, String contentType, String urlStr, String body) throws MalformedURLException, IOException { HttpURLConnection postCon = (HttpURLConnection) new URL(getUrl(urlStr)).openConnection(); postCon.setRequestMethod(method); postCon.setDoOutput(true); postCon.setDoInput(true); if (cookie != null) { postCon.setRequestProperty("Cookie", cookie); if (contentType != null) { postCon.setRequestProperty("Content-type", contentType); } postCon.setRequestProperty("Content-Length", body == null ? "0" : Integer.toString(body.length())); } if (body != null) { OutputStream os = postCon.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os); out.write(body); out.close(); } InputStream is = null; try { is = postCon.getInputStream(); } catch (IOException ioe) { is = postCon.getErrorStream(); } int resCode = postCon.getResponseCode(); if (resCode == 201 || resCode == 202) { String loc = postCon.getHeaderField("Location"); System.out.println("loc:" + loc); return loc; } StringBuffer sb = StreamUtil.readStream(is); return sb.toString(); } Code Sample 2: private void trainDepParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractDepParser parser = null; OneVsAllDecoder decoder = null; if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, s_featureXml); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, s_featureXml); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, ENTRY_LEXICA); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, ENTRY_LEXICA); } else if (flag == ShiftPopParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train conditional"); decoder = new OneVsAllDecoder(m_model); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, t_map, decoder); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = null; DepTree tree; int n; if (s_format.equals(AbstractReader.FORMAT_DEP)) reader = new DepReader(s_trainFile, true); else if (s_format.equals(AbstractReader.FORMAT_CONLLX)) reader = new CoNLLXReader(s_trainFile, true); parser.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { parser.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- parsing: " + n); if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("- saving"); parser.saveTags(ENTRY_LEXICA); t_xml = parser.getDepFtrXml(); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE || flag == ShiftPopParser.FLAG_TRAIN_BOOST) { a_yx = parser.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_PARSER)); PrintStream fout = new PrintStream(zout); fout.print(s_depParser); fout.flush(); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_LEXICA)); IOUtils.copy(new FileInputStream(ENTRY_LEXICA), zout); zout.closeArchiveEntry(); if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) t_map = parser.getDepFtrMap(); } }
11
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: private String md5(String value) { String md5Value = "1"; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(value.getBytes()); md5Value = getHex(digest.digest()); } catch (Exception e) { e.printStackTrace(); } return md5Value; }
11
Code Sample 1: private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static String encriptaSenha(String string) throws ApplicationException { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(string.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); throw new ApplicationException("Erro ao Encriptar Senha"); } } Code Sample 2: private static String md5(String text) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes("UTF-8")); byte[] messageDigest = digest.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static String hash(String string, String algorithm, String encoding) throws UnsupportedEncodingException { try { MessageDigest digest = MessageDigest.getInstance(algorithm); digest.update(string.getBytes(encoding)); byte[] encodedPassword = digest.digest(); return new BigInteger(1, encodedPassword).toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public void copyFile(File a_fileSrc, File a_fileDest, boolean a_append) throws IOException { a_fileDest.getParentFile().mkdirs(); FileInputStream in = null; FileOutputStream out = null; FileChannel fcin = null; FileChannel fcout = null; try { in = new FileInputStream(a_fileSrc); out = new FileOutputStream(a_fileDest, a_append); fcin = in.getChannel(); fcout = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024); while (true) { buffer.clear(); int r = fcin.read(buffer); if (r == -1) { break; } buffer.flip(); fcout.write(buffer); } } catch (IOException ex) { throw ex; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } } } Code Sample 2: public void invoke(InputStream is) throws AgentException { try { addHeader("Content-Type", "application/zip"); addHeader("Content-Length", String.valueOf(is.available())); connection.setDoOutput(true); connection.connect(); OutputStream os = connection.getOutputStream(); boolean success = false; try { IOUtils.copy(is, os); success = true; } finally { try { os.flush(); os.close(); } catch (IOException x) { if (success) throw x; } } connection.disconnect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AgentException("Failed to execute REST call at " + connection.getURL() + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (ConnectException e) { throw new AgentException("Failed to connect to beehive at " + connection.getURL()); } catch (IOException e) { throw new AgentException("Failed to connect to beehive", e); } }
00
Code Sample 1: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: 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); } }
11
Code Sample 1: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } } Code Sample 2: private InputStream open(String url) throws IOException { debug(url); if (!useCache) { return new URL(url).openStream(); } File f = new File(System.getProperty("java.io.tmpdir", "."), Digest.SHA1.encrypt(url) + ".xml"); debug("Cache : " + f); if (f.exists()) { return new FileInputStream(f); } InputStream in = new URL(url).openStream(); OutputStream out = new FileOutputStream(f); IOUtils.copyTo(in, out); out.flush(); out.close(); in.close(); return new FileInputStream(f); }
00
Code Sample 1: @Test public void testHandleMessageInvalidSignature() throws Exception { KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass")).andStubReturn(AuditTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass")).andStubReturn(SignatureTestService.class.getName()); EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address"); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); byte[] document = "hello world".getBytes(); byte[] digestValue = messageDigest.digest(document); EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE)).andStubReturn(digestValue); EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE)).andStubReturn("SHA-1"); SignatureDataMessage message = new SignatureDataMessage(); message.certificateChain = new LinkedList<X509Certificate>(); message.certificateChain.add(certificate); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update("foobar-document".getBytes()); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest); AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); try { this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession); fail(); } catch (ServletException e) { LOG.debug("expected exception: " + e.getMessage()); EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest); assertNull(SignatureTestService.getSignatureValue()); assertEquals("remote-address", AuditTestService.getAuditSignatureRemoteAddress()); assertEquals(certificate, AuditTestService.getAuditSignatureClientCertificate()); } } Code Sample 2: public OAIRecord getRecord(String identifier, String metadataPrefix) throws OAIException { PrefixResolverDefault prefixResolver; XPath xpath; XPathContext xpathSupport; int ctxtNode; XObject list; Node node; OAIRecord rec = new OAIRecord(); priCheckBaseURL(); String params = priBuildParamString("", "", "", identifier, metadataPrefix); try { URL url = new URL(strBaseURL + "?verb=GetRecord" + params); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); if (validation == VALIDATION_VERY_STRICT) { docFactory.setValidating(true); } else { docFactory.setValidating(false); } DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document xml = null; try { xml = docBuilder.parse(http.getInputStream()); rec.frndSetValid(true); } catch (IllegalArgumentException iae) { throw new OAIException(OAIException.CRITICAL_ERR, iae.getMessage()); } catch (SAXException se) { if (validation != VALIDATION_LOOSE) { throw new OAIException(OAIException.XML_PARSE_ERR, se.getMessage()); } else { try { url = new URL(strBaseURL + "?verb=GetRecord" + params); http.disconnect(); http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); xml = docBuilder.parse(priCreateDummyGetRecord(identifier, http.getInputStream())); rec.frndSetValid(false); } catch (SAXException se2) { throw new OAIException(OAIException.XML_PARSE_ERR, se2.getMessage()); } } } try { namespaceNode = xml.createElement("GetRecord"); namespaceNode.setAttribute("xmlns:oai", XMLNS_OAI + "GetRecord"); namespaceNode.setAttribute("xmlns:dc", XMLNS_DC); prefixResolver = new PrefixResolverDefault(namespaceNode); xpath = new XPath("/oai:GetRecord/oai:record", null, prefixResolver, XPath.SELECT, null); xpathSupport = new XPathContext(); ctxtNode = xpathSupport.getDTMHandleFromNode(xml); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { namespaceNode.setAttribute("xmlns:oai", XMLNS_OAI_2_0); prefixResolver = new PrefixResolverDefault(namespaceNode); xpath = new XPath("/oai:OAI-PMH/oai:GetRecord/oai:record", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { namespaceNode.setAttribute("xmlns:oai", XMLNS_OAI_1_0 + "GetRecord"); prefixResolver = new PrefixResolverDefault(namespaceNode); xpath = new XPath("/oai:GetRecord/oai:record", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); } else { xpath = new XPath("oai:OAI-PMH/oai:error", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); ixmlErrors = list.nodelist(); if (ixmlErrors.getLength() > 0) { strProtocolVersion = "2"; throw new OAIException(OAIException.OAI_ERR, getLastOAIError().getCode() + ": " + getLastOAIError().getReason()); } } } if (node != null) { rec.frndSetRepository(this); rec.frndSetMetadataPrefix(metadataPrefix); rec.frndSetIdOnly(false); ctxtNode = xpathSupport.getDTMHandleFromNode(node); xpath = new XPath("//oai:header/oai:identifier", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); rec.frndSetIdentifier(list.nodeset().nextNode().getFirstChild().getNodeValue()); xpath = new XPath("//oai:header/oai:datestamp", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); rec.frndSetDatestamp(list.nodeset().nextNode().getFirstChild().getNodeValue()); rec.frndSetRecord(node); NamedNodeMap nmap = node.getAttributes(); if (nmap != null) { if (nmap.getNamedItem("status") != null) { rec.frndSetStatus(nmap.getNamedItem("status").getFirstChild().getNodeValue()); } } } else { rec = null; } xpath = new XPath("//oai:responseDate", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strResponseDate = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strResponseDate = ""; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing responseDate"); } } xpath = new XPath("//oai:requestURL | //oai:request", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { ixmlRequest = node; } else { if (validation == VALIDATION_LOOSE) { ixmlRequest = null; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing requestURL"); } } xpath = null; prefixResolver = null; xpathSupport = null; list = null; } catch (TransformerException te) { throw new OAIException(OAIException.CRITICAL_ERR, te.getMessage()); } url = null; docFactory = null; docBuilder = null; } catch (MalformedURLException mue) { throw new OAIException(OAIException.CRITICAL_ERR, mue.getMessage()); } catch (FactoryConfigurationError fce) { throw new OAIException(OAIException.CRITICAL_ERR, fce.getMessage()); } catch (ParserConfigurationException pce) { throw new OAIException(OAIException.CRITICAL_ERR, pce.getMessage()); } catch (IOException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } return rec; }
00
Code Sample 1: public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } Code Sample 2: public static String encryptPassword(String password) { String hash = null; try { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = Base64.encode(raw, false); } catch (Exception e) { } return hash; }
00
Code Sample 1: private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private boolean doPost(String content) throws IOException { logger.debug("Service Registry PutRecordHandler: " + baseurl.toString()); logger.debug("**** Service Registry PutRecord Request ****\n " + content); HttpURLConnection huc = (HttpURLConnection) (baseurl.openConnection()); huc.setRequestMethod("POST"); huc.setDoOutput(true); ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes()); OutputStream out = huc.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream bis = new BufferedInputStream(in); int count = 0; while ((count = bis.read(buffer)) != -1) { out.write(buffer, 0, count); } out.close(); int code = huc.getResponseCode(); logger.debug("Service Registry Response Code: " + code); if (code == 200) { return true; } else return false; }
00
Code Sample 1: public UpdaterView(SingleFrameApplication app, String[] args) { super(app); if (args.length != 3) { System.out.println("Args must be passed."); System.exit(1); } else { currentVersion = Double.parseDouble(args[0]); currentDBVersion = Double.parseDouble(args[1]); dbAdmin = args[2].equals("true") ? true : false; } initComponents(); try { URL url = new URL(BASE_URL + "version.txt"); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); String tmp = ""; int data = buffIn.read(); while (data != -1) { tmp = tmp.concat(Character.toString((char) data)); data = buffIn.read(); } String[] versionEntries = tmp.split("\n"); if (versionEntries.length > 0) { String[] components = versionEntries[0].split(":"); if (dbAdmin || Double.parseDouble(components[4]) == currentDBVersion) { byteCount = Integer.parseInt(components[2]); lblCurrent.setText(new Double(currentVersion).toString()); lblLatest.setText(components[0]); latestVersionNum = Double.parseDouble(components[0]); lblNotes.setText("<html>" + components[1]); md5Hash = components[3]; latestDBVersion = Double.parseDouble(components[4]); upgradeURL = components[5]; progressBar.setMaximum(byteCount); if (dbAdmin && Double.parseDouble(components[4]) > currentDBVersion) { schemaUpdatesNeeded = true; schemaChanges.addFirst(latestDBVersion); double lastVersion = latestDBVersion; for (int i = 1; i < versionEntries.length; i++) { components = versionEntries[i].split(":"); double nextVers = Double.parseDouble(components[4]); if (nextVers != currentDBVersion) { if (lastVersion != nextVers) { schemaChanges.addFirst(nextVers); lastVersion = nextVers; } } else { schemaChanges.addFirst(currentDBVersion); break; } } } } else { for (int i = 1; i < versionEntries.length; i++) { components = versionEntries[i].split(":"); if (Double.parseDouble(components[4]) == currentDBVersion) { byteCount = Integer.parseInt(components[2]); lblCurrent.setText(new Double(currentVersion).toString()); lblLatest.setText(components[0]); latestVersionNum = Double.parseDouble(components[0]); lblNotes.setText("<html>" + components[1]); md5Hash = components[3]; latestDBVersion = Double.parseDouble(components[4]); upgradeURL = components[5]; progressBar.setMaximum(byteCount); schemaUpdatesNeeded = true; break; } } } } else { throw new InvalidUpdateFileFormatException("File Format is Wrong."); } if (latestVersionNum == currentVersion) { if (schemaUpdatesNeeded) { javax.swing.JOptionPane.showMessageDialog(super.getComponent(), "Updates are available but they require database changes. Please contact your system administrator to perform the upgrade.", "Myopa Updater", javax.swing.JOptionPane.INFORMATION_MESSAGE); } else { javax.swing.JOptionPane.showMessageDialog(super.getComponent(), "No Updates are available - your software is up to date!", "Myopa Updater", javax.swing.JOptionPane.INFORMATION_MESSAGE); } System.exit(0); } else { jButton1.setEnabled(true); } } catch (InvalidUpdateFileFormatException e) { } catch (MalformedURLException e) { System.out.println("EXCP " + e); } catch (IOException io) { System.out.println("IO" + io); } ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String) (evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer) (evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); } Code Sample 2: public static void postData(Reader data, URL endpoint, Writer output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endpoint.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlc != null) urlc.disconnect(); } }
11
Code Sample 1: public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } 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: protected void givenTestRepository(String repositoryId) throws Exception { HttpResponse response = executeDeleteWithResponse("/repositories/" + repositoryId); consume(response.getEntity()); response = executePost("/repositories", createRepositoryXml(repositoryId)); assertEquals(content(response), SC_CREATED, statusCode(response)); } Code Sample 2: public void testReceiveMessageWithHttpPost() throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://192.167.131.126/hotel/sms/create.htm"); String receipt = "2#12345:source:079456345:200:xxx:1234567809:userfred:"; String message = "11796 book owner2 password 238 12.09.2008 3 testname surname"; HttpParams params = new BasicHttpParams(); params.setParameter("TextMessage", message); httpPost.setParams(params); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); }
11
Code Sample 1: public static void copyFile(String original, String destination) throws Exception { File original_file = new File(original); File destination_file = new File(destination); if (!original_file.exists()) throw new Exception("File with path " + original + " does not exist."); if (destination_file.exists()) throw new Exception("File with path " + destination + " already exists."); FileReader in = new FileReader(original_file); FileWriter out = new FileWriter(destination_file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) throws IOException { boolean resultat = false; FileInputStream fis = new FileInputStream(sRC2); FileOutputStream fos = new FileOutputStream(dEST2); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); progressEnCours.setValue(0); progressEnCours.setString(sRC2 + " : 0 %"); channelSrc.transferTo(0, channelSrc.size(), channelDest); progressEnCours.setValue(100); progressEnCours.setString(sRC2 + " : 100 %"); if (channelSrc.size() == channelDest.size()) { resultat = true; } else { resultat = false; } fis.close(); fos.close(); return (resultat); }