label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
|
Code Sample 1:
private void publishCMap(LWMap map) throws IOException { try { File savedCMap = PublishUtil.createIMSCP(Publisher.resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("IMSCP", "zip"))); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } catch (IOException ex) { throw ex; } catch (Exception ex) { System.out.println(ex); VueUtil.alert(VUE.getDialogParent(), VueResources.getString("dialog.export.message") + ex.getMessage(), VueResources.getString("dialog.export.title"), JOptionPane.ERROR_MESSAGE); } }
Code Sample 2:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
|
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 concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
|
11
|
Code Sample 1:
public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
Code Sample 2:
public static File copyFile(File fileToCopy, File copiedFile) { BufferedInputStream in = null; BufferedOutputStream outWriter = null; if (!copiedFile.exists()) { try { copiedFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } } try { in = new BufferedInputStream(new FileInputStream(fileToCopy), 4096); outWriter = new BufferedOutputStream(new FileOutputStream(copiedFile), 4096); int c; while ((c = in.read()) != -1) outWriter.write(c); in.close(); outWriter.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } return copiedFile; }
|
00
|
Code Sample 1:
public void process(String dir) { String[] list = new File(dir).list(); if (list == null) return; int n = list.length; long[] bubblesort = new long[list.length + 1]; if (!statustext) { IJ.log("Current Directory is: " + dir); IJ.log(" "); IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick); IJ.log(" "); } for (int i = 0; i < n; i++) { IJ.showStatus(i + "/" + n); File f = new File(dir + list[i]); if (!f.isDirectory()) { ImagePlus img = new Opener().openImage(dir, list[i]); if (img != null && img.getStackSize() == 1) { if (!scoutengine(img)) return; if (!statustext) { IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase); } int lastDigit = whichcase.length() - 1; while (lastDigit > 0) { if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break; } if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1); bubblesort[i] = Long.parseLong(whichcase); } } } if (statussorta || statussortd || statustext) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (statussorta) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } else { if (bubblesort[i] < bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } } IJ.log(" "); for (int i = 0; i < n; i++) { if (!statustext) { IJ.log(list[i] + " / " + bubblesort[i]); } else { IJ.log(dir + list[i]); } } } if (open_as_stack || only_images) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } if (only_images) { Opener o = new Opener(); int counter = 0; IJ.log(" "); for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; else { ImagePlus imp = o.openImage(path); counter++; if (imp != null) { IJ.log(counter + " + " + path); imp.show(); } else IJ.log(counter + " - " + path); } } return; } int width = 0, height = 0, type = 0; ImageStack stack = null; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int k = 0; try { for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; if (list[i].endsWith(".txt")) continue; ImagePlus imp = new Opener().openImage(path); if (imp != null && stack == null) { width = imp.getWidth(); height = imp.getHeight(); type = imp.getType(); ColorModel cm = imp.getProcessor().getColorModel(); if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm); } if (stack != null) k = stack.getSize() + 1; IJ.showStatus(k + "/" + n); IJ.showProgress((double) k / n); if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else { ImageProcessor ip = imp.getProcessor(); if (grayscale) ip = ip.convertToByte(true); if (halfSize) ip = ip.resize(width / 2, height / 2); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); String label = imp.getTitle(); String info = (String) imp.getProperty("Info"); if (info != null) label += "\n" + info; stack.addSlice(label, ip); } System.gc(); } } catch (OutOfMemoryError e) { IJ.outOfMemory("FolderOpener"); stack.trim(); } if (stack != null && stack.getSize() > 0) { ImagePlus imp2 = new ImagePlus("Stack", stack); if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max); imp2.show(); } IJ.showProgress(1.0); } }
Code Sample 2:
public ViewedCandidatesIndex getAllViewedCandidates() throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpGet req = new HttpGet(remoteHost.getUrl() + "/cand/viewed"); req.setHeader("Accept-Encoding", "gzip"); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof ViewedCandidatesIndex) { ViewedCandidatesIndex p = (ViewedCandidatesIndex) xmlable; return p; } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for ViewedCandidatesIndex"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } }
|
11
|
Code Sample 1:
private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
|
00
|
Code Sample 1:
public boolean addFavBoard(BoardObject board) throws NetworkException, ContentException { String url = HttpConfig.bbsURL() + HttpConfig.BBS_FAV_ADD + board.getId(); HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response) && HTTPUtil.isXmlContentType(response)) { HTTPUtil.consume(response.getEntity()); return true; } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
private BibtexDatabase importInspireEntries(String key, OutputPrinter frame) { String url = constructUrl(key); try { HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Jabref"); InputStream inputStream = conn.getInputStream(); INSPIREBibtexFilterReader reader = new INSPIREBibtexFilterReader(new InputStreamReader(inputStream)); ParserResult pr = BibtexParser.parse(reader); return pr.getDatabase(); } catch (IOException e) { frame.showMessage(Globals.lang("An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (RuntimeException e) { frame.showMessage(Globals.lang("An Error occurred while fetching from INSPIRE source (%0):", new String[] { url }) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } return null; }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
private void addAllSpecialPages(Environment env, ZipOutputStream zipout, int progressStart, int progressLength) throws Exception, IOException { ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale); String tpl; int count = 0; int numberOfSpecialPages = 7; progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; String cssContent = wb.readRaw(virtualWiki, "StyleSheet"); addZipEntry(zipout, "css/vqwiki.css", cssContent); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; tpl = getTemplateFilledWithContent("search"); addTopicEntry(zipout, tpl, "WikiSearch", "WikiSearch.html"); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; zipout.putNextEntry(new ZipEntry("applets/export2html-applet.jar")); IOUtils.copy(new FileInputStream(ctx.getRealPath("/WEB-INF/classes/export2html/export2html-applet.jar")), zipout); zipout.closeEntry(); zipout.flush(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JarOutputStream indexjar = new JarOutputStream(bos); JarEntry jarEntry; File searchDir = new File(wb.getSearchEngine().getSearchIndexPath(virtualWiki)); String files[] = searchDir.list(); StringBuffer listOfAllFiles = new StringBuffer(); for (int i = 0; i < files.length; i++) { if (listOfAllFiles.length() > 0) { listOfAllFiles.append(","); } listOfAllFiles.append(files[i]); jarEntry = new JarEntry("lucene/index/" + files[i]); indexjar.putNextEntry(jarEntry); IOUtils.copy(new FileInputStream(new File(searchDir, files[i])), indexjar); indexjar.closeEntry(); } indexjar.flush(); indexjar.putNextEntry(new JarEntry("lucene/index.dir")); IOUtils.copy(new StringReader(listOfAllFiles.toString()), indexjar); indexjar.closeEntry(); indexjar.flush(); indexjar.close(); zipout.putNextEntry(new ZipEntry("applets/index.jar")); zipout.write(bos.toByteArray()); zipout.closeEntry(); zipout.flush(); bos.reset(); } catch (Exception e) { logger.log(Level.FINE, "Exception while adding lucene index: ", e); } progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; StringBuffer content = new StringBuffer(); content.append("<table><tr><th>" + messages.getString("common.date") + "</th><th>" + messages.getString("common.topic") + "</th><th>" + messages.getString("common.user") + "</th></tr>" + IOUtils.LINE_SEPARATOR); Collection all = null; try { Calendar cal = Calendar.getInstance(); ChangeLog cl = wb.getChangeLog(); int n = env.getIntSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS); if (n == 0) { n = 5; } all = new ArrayList(); for (int i = 0; i < n; i++) { Collection col = cl.getChanges(virtualWiki, cal.getTime()); if (col != null) { all.addAll(col); } cal.add(Calendar.DATE, -1); } } catch (Exception e) { } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); for (Iterator iter = all.iterator(); iter.hasNext(); ) { Change change = (Change) iter.next(); content.append("<tr><td class=\"recent\">" + df.format(change.getTime()) + "</td><td class=\"recent\"><a href=\"" + safename(change.getTopic()) + ".html\">" + change.getTopic() + "</a></td><td class=\"recent\">" + change.getUser() + "</td></tr>"); } content.append("</table>" + IOUtils.LINE_SEPARATOR); tpl = getTemplateFilledWithContent(null); tpl = tpl.replaceAll("@@CONTENTS@@", content.toString()); addTopicEntry(zipout, tpl, "RecentChanges", "RecentChanges.html"); logger.fine("Done adding all special topics."); }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { if (T.t) T.info("Copying " + src + " -> " + dst + "..."); FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); byte buf[] = new byte[40 * KB]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); } out.flush(); out.close(); in.close(); if (T.t) T.info("File copied."); }
Code Sample 2:
public void importCertFile(File file) throws IOException { File kd; File cd; synchronized (this) { kd = keysDir; cd = certsDir; } if (!cd.isDirectory()) { kd.mkdirs(); cd.mkdirs(); } String newName = file.getName(); File dest = new File(cd, newName); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(file).getChannel(); destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public RobotList<Resource> sort_incr_Resource(RobotList<Resource> list, String field) { int length = list.size(); Index_value[] resource_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, distance(cur_loc, list.get(i).location)); } } else if (field.equals("energy")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).energy); } } else if (field.equals("ammostash")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).ammostash); } } else if (field.equals("speed")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).speed); } } else if (field.equals("health")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).health); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (resource_dist[i].value > resource_dist[i + 1].value) { Index_value a = resource_dist[i]; resource_dist[i] = resource_dist[i + 1]; resource_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Resource> new_resource_list = new RobotList<Resource>(Resource.class); for (int i = 0; i < length; i++) { new_resource_list.addLast(list.get(resource_dist[i].index)); } return new_resource_list; }
Code Sample 2:
public final String encrypt(final String plaintext, final String salt) { if (plaintext == null) { throw new NullPointerException(); } if (salt == null) { throw new NullPointerException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update((plaintext + salt).getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public Reader transform(Reader reader, Map<String, Object> parameterMap) { try { File file = File.createTempFile("srx2", ".srx"); file.deleteOnExit(); Writer writer = getWriter(getFileOutputStream(file.getAbsolutePath())); transform(reader, writer, parameterMap); writer.close(); Reader resultReader = getReader(getFileInputStream(file.getAbsolutePath())); return resultReader; } catch (IOException e) { throw new IORuntimeException(e); } }
|
00
|
Code Sample 1:
public static int gzipFile(File file_input, String file_output) { File gzip_output = new File(file_output); GZIPOutputStream gzip_out_stream; try { FileOutputStream out = new FileOutputStream(gzip_output); gzip_out_stream = new GZIPOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) gzip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_GZIP_FAIL; } try { gzip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; }
Code Sample 2:
private void getRandomGuid(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = secureRandom.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); String 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)); } guid = sb.toString(); }
|
00
|
Code Sample 1:
private String readLine(final String urlStr) { BufferedReader reader; String line = null; try { URL url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream())); line = reader.readLine(); } catch (MalformedURLException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } return line; }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
public static boolean copyFile(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; boolean retour = false; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); retour = true; } catch (IOException e) { System.err.println("File : " + fileIn); e.printStackTrace(); } return retour; }
Code Sample 2:
public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
11
|
Code Sample 1:
public File takeFile(File f, String prefix, String suffix) throws IOException { File nf = createNewFile(prefix, suffix); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); FileOutputStream fos = new FileOutputStream(nf); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); f.delete(); return nf; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
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 void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public static String calculateSHA1(String data, String key) throws NoSuchAlgorithmException, UnsupportedEncodingException { data += key; MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(data.getBytes("iso-8859-1"), 0, data.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
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; }
|
00
|
Code Sample 1:
public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public byte[] loadResource(String location) throws IOException { if ((location == null) || (location.length() == 0)) { throw new IOException("The given resource location must not be null and non empty."); } URL url = buildURL(location); URLConnection cxn = url.openConnection(); InputStream is = null; try { byte[] byteBuffer = new byte[2048]; ByteArrayOutputStream bos = new ByteArrayOutputStream(2048); is = cxn.getInputStream(); int bytesRead = 0; while ((bytesRead = is.read(byteBuffer, 0, 2048)) >= 0) { bos.write(byteBuffer, 0, bytesRead); } return bos.toByteArray(); } finally { if (is != null) { is.close(); } } }
|
00
|
Code Sample 1:
public void setTypeRefs(Connection conn) { log.traceln("\tProcessing " + table + " references.."); try { String query = " select distinct c.id, c.qualifiedname from " + table + ", CLASSTYPE c " + " where " + table + "." + reffield + " is null and " + table + "." + classnamefield + " = c.qualifiedname"; PreparedStatement pstmt = conn.prepareStatement(query); long start = new Date().getTime(); ResultSet rset = pstmt.executeQuery(); long queryTime = new Date().getTime() - start; log.debug("query time: " + queryTime + " ms"); String update = "update " + table + " set " + reffield + "=? where " + classnamefield + "=? and " + reffield + " is null"; PreparedStatement pstmt2 = conn.prepareStatement(update); int n = 0; start = new Date().getTime(); while (rset.next()) { n++; pstmt2.setInt(1, rset.getInt(1)); pstmt2.setString(2, rset.getString(2)); pstmt2.executeUpdate(); } queryTime = new Date().getTime() - start; log.debug("total update time: " + queryTime + " ms"); log.debug("number of times through loop: " + n); if (n > 0) log.debug("avg update time: " + (queryTime / n) + " ms"); pstmt2.close(); rset.close(); pstmt.close(); conn.commit(); log.verbose("Updated (committed) " + table + " references"); } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }
Code Sample 2:
public static void writeFromURL(String urlstr, String filename) throws Exception { URL url = new URL(urlstr); InputStream in = url.openStream(); BufferedReader bf = null; StringBuffer sb = new StringBuffer(); try { bf = new BufferedReader(new InputStreamReader(in, "latin1")); String s; while (true) { s = bf.readLine(); if (s != null) { sb.append(s); } else { break; } } } catch (Exception e) { throw e; } finally { bf.close(); } writeRawBytes(sb.toString(), filename); }
|
11
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
Code Sample 2:
public String copyImages(Document doc, String sXML, String newPath, String tagName, String itemName) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { nl = doc.getElementsByTagName(tagName); for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem(itemName); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath; if (itemName.equals("data")) sSourcePath = sOldPath; else sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = newPath + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } sXML = sXML.replace(nsrc.getTextContent(), sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sXML; }
|
11
|
Code Sample 1:
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
Code Sample 2:
@Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + httpServletRequest.getQueryString()); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + baos.toString()); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
|
00
|
Code Sample 1:
private boolean isReservaOK(String urlAddress, String operationId, String idioma, String codigo_pedido, String merchantId) throws ServletException { StringBuffer buf = new StringBuffer(); try { URL url = new URL(urlAddress + "?Num_operacion=" + operationId + "&Idioma=" + idioma + "&Codigo_pedido=" + codigo_pedido + "&MerchantID=" + merchantId); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { buf.append(str); } in.close(); } catch (IOException e) { throw new ServletException(e); } return buf.indexOf("$*$OKY$*$") != -1; }
Code Sample 2:
public void sendResponse(DjdocRequest req, HttpServletResponse res) throws IOException { File file = (File) req.getResult(); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) { in.close(); } } }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
|
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:
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 static URL lookForDefaultThemeFile(String aFilename) { try { XPathFactory fabrique = XPathFactory.newInstance(); XPath environnement = fabrique.newXPath(); URL url = new URL("file:" + aFilename); InputSource source = new InputSource(url.openStream()); XPathExpression expression; expression = environnement.compile("/alloy/instance/@filename"); String resultat = expression.evaluate(source); AlloyPlugin.getDefault().logInfo("Solution coming from " + resultat); IPath path = new Path(resultat); IPath themePath = path.removeFileExtension().addFileExtension("thm"); File themeFile = themePath.toFile(); if (themeFile.exists()) { AlloyPlugin.getDefault().logInfo("Found default theme " + themeFile); return themeFile.toURI().toURL(); } } catch (MalformedURLException e) { AlloyPlugin.getDefault().log(e); } catch (IOException e) { AlloyPlugin.getDefault().log(e); } catch (XPathExpressionException e) { AlloyPlugin.getDefault().log(e); } return null; }
Code Sample 2:
@SuppressWarnings("unchecked") public HttpResponse putFile(String root, String to_path, File file_obj) throws DropboxException { String path = "/files/" + root + to_path; try { Path targetPath = new Path(path); String target = buildFullURL(secureProtocol, content_host, port, buildURL(targetPath.removeLastSegments(1).addTrailingSeparator().toString(), API_VERSION, null)); HttpClient client = getClient(target); HttpPost req = new HttpPost(target); List nvps = new ArrayList(); nvps.add(new BasicNameValuePair("file", targetPath.lastSegment())); req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); auth.sign(req); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(file_obj, targetPath.lastSegment(), "application/octet-stream", null); entity.addPart("file", bin); req.setEntity(entity); HttpResponse resp = client.execute(req); resp.getEntity().consumeContent(); return resp; } catch (Exception e) { throw new DropboxException(e); } }
|
00
|
Code Sample 1:
public static void readAsFile(String fileName, String url) { BufferedInputStream in = null; BufferedOutputStream out = null; URLConnection conn = null; try { conn = new URL(url).openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(fileName)); int b; while ((b = in.read()) != -1) { out.write(b); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { } } } }
Code Sample 2:
private static MappedObject sendHttpRequestToUrl(URL url, String method) throws Exception { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.connect(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder buffer = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } System.out.println("Read: " + buffer.toString()); connection.disconnect(); JAXBContext context = JAXBContext.newInstance(MappedObject.class); Unmarshaller unmarshaller = context.createUnmarshaller(); MappedObject mapped = (MappedObject) unmarshaller.unmarshal(new StringReader(buffer.toString())); return mapped; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Could not establish connection to " + url.toExternalForm()); }
|
00
|
Code Sample 1:
public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(Options.fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public static String deleteTag(String tag_id) { String so = OctopusErrorMessages.UNKNOWN_ERROR; if (tag_id == null || tag_id.trim().equals("")) { return OctopusErrorMessages.TAG_ID_CANT_BE_EMPTY; } DBConnection theConnection = null; try { theConnection = DBServiceManager.allocateConnection(); theConnection.setAutoCommit(false); String query = "DELETE FROM tr_translation WHERE tr_translation_trtagid=?"; PreparedStatement state = theConnection.prepareStatement(query); state.setString(1, tag_id); state.executeUpdate(); String query2 = "DELETE FROM tr_tag WHERE tr_tag_id=? "; PreparedStatement state2 = theConnection.prepareStatement(query2); state2.setString(1, tag_id); state2.executeUpdate(); theConnection.commit(); so = OctopusErrorMessages.ACTION_DONE; } catch (SQLException e) { try { theConnection.rollback(); } catch (SQLException ex) { } so = OctopusErrorMessages.ERROR_DATABASE; } finally { if (theConnection != null) { try { theConnection.setAutoCommit(true); } catch (SQLException ex) { } theConnection.release(); } } return so; }
|
11
|
Code Sample 1:
public static Hashtable DefaultLoginValues(String firstName, String lastName, String password, String mac, String startLocation, int major, int minor, int patch, int build, String platform, String viewerDigest, String userAgent, String author) throws Exception { Hashtable values = new Hashtable(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes("ASCII"), 0, password.length()); byte[] raw_digest = md5.digest(); String passwordDigest = Helpers.toHexText(raw_digest); values.put("first", firstName); values.put("last", lastName); values.put("passwd", "" + password); values.put("start", startLocation); values.put("major", major); values.put("minor", minor); values.put("patch", patch); values.put("build", build); values.put("platform", platform); values.put("mac", mac); values.put("agree_to_tos", "true"); values.put("viewer_digest", viewerDigest); values.put("user-agent", userAgent + " (" + Helpers.VERSION + ")"); values.put("author", author); Vector optionsArray = new Vector(); optionsArray.addElement("inventory-root"); optionsArray.addElement("inventory-skeleton"); optionsArray.addElement("inventory-lib-root"); optionsArray.addElement("inventory-lib-owner"); optionsArray.addElement("inventory-skel-lib"); optionsArray.addElement("initial-outfit"); optionsArray.addElement("gestures"); optionsArray.addElement("event_categories"); optionsArray.addElement("event_notifications"); optionsArray.addElement("classified_categories"); optionsArray.addElement("buddy-list"); optionsArray.addElement("ui-config"); optionsArray.addElement("login-flags"); optionsArray.addElement("global-textures"); values.put("options", optionsArray); return values; }
Code Sample 2:
public static String generate(String source) { byte[] SHA = new byte[20]; String SHADigest = ""; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); for (int i = 0; i < SHA.length; i++) SHADigest += (char) SHA[i]; } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } return SHADigest; }
|
11
|
Code Sample 1:
public static String hashValue(String password, String salt) throws TeqloException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); md.update(salt.getBytes("UTF-8")); byte raw[] = md.digest(); char[] encoded = (new BASE64Encoder()).encode(raw).toCharArray(); int length = encoded.length; while (length > 0 && encoded[length - 1] == '=') length--; for (int i = 0; i < length; i++) { if (encoded[i] == '+') encoded[i] = '*'; else if (encoded[i] == '/') encoded[i] = '-'; } return new String(encoded, 0, length); } catch (Exception e) { throw new TeqloException("Security", "password", e, "Could not process password"); } }
Code Sample 2:
public String encripta(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } }
|
00
|
Code Sample 1:
public void testFileSystem() throws IOException { Fragment f = Fragment.EMPTY; Fragment g = f.plus(System.getProperty("java.io.tmpdir")); Fragment h = f.plus("april", "1971", "data.txt"); Fragment i = f.plus(g, h); InOutLocation iol = locs.fs.plus(i); PrintStream ps = new PrintStream(iol.openOutput()); List<String> expected = new ArrayList<String>(); expected.add("So I am stepping out this old brown shoe"); expected.add("Maybe I'm in love with you"); for (String s : expected) ps.println(s); ps.close(); InLocation inRoot = locs.fs; List<String> lst = read(inRoot.plus(i).openInput()); assertEquals(expected, lst); URL url = iol.toUrl(); lst = read(url.openStream()); assertEquals(expected, lst); }
Code Sample 2:
public static String getUserToken(String userName) { if (userName != null && userName.trim().length() > 0) try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update((userName + seed).getBytes("ISO-8859-1")); return BaseController.bytesToHex(md.digest()); } catch (NullPointerException npe) { } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; }
|
00
|
Code Sample 1:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
Code Sample 2:
public static String unsecureHashConstantSalt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT3 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT4; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpMethod httpMethod; if (isPost || isPut) { EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e) : new InputStreamRequestEntity(e, Long.parseLong(length))); excerpt = e.getExcerpt(); } httpMethod = entityEnclosingMethod; } else if (isDelete) { httpMethod = new DeleteMethod(url); } else { httpMethod = new GetMethod(url); } for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { httpMethod.setFollowRedirects(Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value)); } } for (Map.Entry<String, String> header : request.headers) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString())); client.executeMethod(httpMethod); return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset()); }
|
00
|
Code Sample 1:
public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } }
Code Sample 2:
public static void readAsFile(String fileName, String url) { BufferedInputStream in = null; BufferedOutputStream out = null; URLConnection conn = null; try { conn = new URL(url).openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(fileName)); int b; while ((b = in.read()) != -1) { out.write(b); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { } } } }
|
11
|
Code Sample 1:
public static String getEncodedHex(String text) { MessageDigest md = null; String encodedString = null; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } Hex hex = new Hex(); encodedString = new String(hex.encode(md.digest())); md.reset(); return encodedString; }
Code Sample 2:
private static String getUnsaltedHash(String algorithm, String input) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.reset(); messageDigest.update(input.getBytes(Main.DEFAULT_CHARSET)); byte[] digest = messageDigest.digest(); return String.format(Main.DEFAULT_LOCALE, "%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); }
|
11
|
Code Sample 1:
protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = super.getDatastreams(pDeposit); FileInputStream tInput = null; String tFileName = ((LocalDatastream) tDatastreams.get(0)).getPath(); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".thum")); tInput.close(); Datastream tThum = new LocalDatastream("THUMBRES_IMG", this.getContentType(), tTempFileName + ".thum"); tDatastreams.add(tThum); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".mid")); tInput.close(); Datastream tMid = new LocalDatastream("MEDRES_IMG", this.getContentType(), tTempFileName + ".mid"); tDatastreams.add(tMid); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".high")); tInput.close(); Datastream tLarge = new LocalDatastream("HIGHRES_IMG", this.getContentType(), tTempFileName + ".high"); tDatastreams.add(tLarge); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".vhigh")); tInput.close(); Datastream tVLarge = new LocalDatastream("VERYHIGHRES_IMG", this.getContentType(), tTempFileName + ".vhigh"); tDatastreams.add(tVLarge); return tDatastreams; }
Code Sample 2:
public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public MytemMaster getMytemMaster(String janCode) throws GaeException { HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); BufferedReader reader = null; StringBuffer request = new StringBuffer(address); request.append("api/mytems/show?jan="); request.append(janCode); try { HttpGet httpGet = new HttpGet(request.toString()); HttpResponse httpResponse = client.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == NOT_FOUND) { return null; } if (statusCode >= 400) { throw new GaeException("Status Error = " + Integer.toString(statusCode)); } reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } return createMytemMaster(builder.toString()); } catch (ClientProtocolException e) { throw new GaeException(e); } catch (SocketTimeoutException e) { throw new GaeException(e); } catch (IOException exception) { throw new GaeException(exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
public IntactOntology parseOboFile(URL url, boolean keepTemporaryFile) throws PsiLoaderException { if (url == null) { throw new IllegalArgumentException("Please give a non null URL."); } StringBuffer buffer = new StringBuffer(1024 * 8); try { System.out.println("Loading URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()), 1024); String line; int lineCount = 0; while ((line = in.readLine()) != null) { lineCount++; buffer.append(line).append(NEW_LINE); if ((lineCount % 20) == 0) { System.out.print("."); System.out.flush(); if ((lineCount % 500) == 0) { System.out.println(" " + lineCount); } } } in.close(); File tempDirectory = new File(System.getProperty("java.io.tmpdir", "tmp")); if (!tempDirectory.exists()) { if (!tempDirectory.mkdirs()) { throw new IOException("Cannot create temp directory: " + tempDirectory.getAbsolutePath()); } } System.out.println("Using temp directory: " + tempDirectory.getAbsolutePath()); File tempFile = File.createTempFile("psimi.v25.", ".obo", tempDirectory); tempFile.deleteOnExit(); tempFile.deleteOnExit(); System.out.println("The OBO file is temporary store as: " + tempFile.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(tempFile), 1024); out.write(buffer.toString()); out.flush(); out.close(); return parseOboFile(tempFile); } catch (IOException e) { throw new PsiLoaderException("Error while loading URL (" + url + ")", e); } }
|
11
|
Code Sample 1:
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); } }
Code Sample 2:
public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; }
|
11
|
Code Sample 1:
public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public static void write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } }
|
00
|
Code Sample 1:
public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
Code Sample 2:
public static Vector<Person> parseFriends(Worker me, SmEngine sme, Person resource) throws IOException { URL url = new URL(resource.getUrl()); long fid; if (sme.getProxy() == null) me.conn = (HttpURLConnection) url.openConnection(); else me.conn = (HttpURLConnection) url.openConnection(sme.getProxy()); me.conn.setReadTimeout(20 * 1000); Vector<Person> result; org.htmlparser.Parser parser; NodeList nl; NodeFilter[] filters1 = new NodeFilter[2]; filters1[0] = new TagNameFilter("a"); filters1[1] = new HasAttributeFilter("class", "signup_btn uiButton uiButtonSpecial uiButtonLarge"); NodeFilter[] filters2 = new NodeFilter[3]; filters2[0] = new TagNameFilter("a"); filters2[1] = new HasAttributeFilter("class", "title"); filters2[2] = new HasParentFilter(new HasAttributeFilter("class", "UIPortrait_Text")); try { parser = new org.htmlparser.Parser(me.conn); } catch (ParserException e) { System.err.println(e.getMessage()); return null; } try { nl = parser.parse(new AndFilter(filters1)); fid = Long.parseLong(((LinkTag) nl.elementAt(0)).getLink().split("(fid=|&)")[2]); } catch (ParserException e) { e.printStackTrace(); return null; } result = new Vector<Person>(); try { nl = parser.parse(new AndFilter(filters2)); } catch (ParserException e) { e.printStackTrace(); return null; } Person p; for (int i = 0; i < nl.size(); i++) { p = sme.getPerson(fid, ((TagNode) nl.elementAt(i)).getAttribute("title"), ((TagNode) nl.elementAt(i)).getAttribute("href")); resource.addFriend(p); p.addFriend(resource); synchronized (p) { if (!p.isInQueue()) { p.setInQueue(true); sme.addResource(p); } } } return result; }
|
00
|
Code Sample 1:
public static String checkUpdate() { URL url = null; try { url = new URL("http://googlemeupdate.bravehost.com/"); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream html = null; try { html = url.openStream(); int c = 0; String Buffer = ""; String Code = ""; while (c != -1) { try { c = html.read(); } catch (IOException ex) { } Buffer = Buffer + (char) c; } return Buffer.substring(Buffer.lastIndexOf("Google.mE Version: ") + 19, Buffer.indexOf("||")); } catch (IOException ex) { ex.printStackTrace(); return ""; } }
Code Sample 2:
public boolean copy(String file, String target, int tag) { try { File file_in = new File(file); File file_out = new File(target); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
|
00
|
Code Sample 1:
public long add(T t) throws BaseException { Connection conn = null; PreparedStatement pstmt = null; long result = -1L; boolean flag = false; try { conn = getConnection(); if (conn != null) { flag = true; } else { conn = ConnectionManager.getConn(getStrConnection()); conn.setAutoCommit(false); } pstmt = getAdd(conn, t, this.getTableName()); pstmt.executeUpdate(); result = t.getId(); } catch (SQLException e) { try { if (!flag) { conn.rollback(); } } catch (Exception ex) { log.error("add(T " + t.toString() + ")回滚出错,错误信息:" + ex.getMessage()); } log.error("add(T " + t.toString() + ")方法出错:" + e.getMessage()); } catch (BaseException e) { throw e; } finally { try { if (!flag) { conn.setAutoCommit(true); } } catch (Exception e) { log.error("add(T " + t.toString() + ")方法设置自动提交出错,信息为:" + e.getMessage()); } ConnectionManager.closePreparedStatement(pstmt); if (!flag) { ConnectionManager.closeConn(conn); } } return result; }
Code Sample 2:
public void getDownloadInfo(String _url) throws Exception { cl = new DefaultHttpClient(); InfoAuthPromter hp = new InfoAuthPromter(); cl.setCredentialsProvider(hp); head = new HttpHead(_url); head.setHeader("User-Agent", "test"); head.setHeader("Accept", "*/*"); head.setHeader("Range", "bytes=0-"); HttpResponse resp = cl.execute(head); ent = resp.getEntity(); int code = resp.getStatusLine().getStatusCode(); if (code == 401) { throw new Exception("HTTP Auth Failed"); } AuthManager.putAuth(getSite(), auth); setURL(head.getURI().toString()); setSize(ent.getContentLength()); setRangeEnd(getSize() - 1); setResumable(code == 206); }
|
00
|
Code Sample 1:
private String httpGet(String urlString, boolean postStatus) throws Exception { URL url; URLConnection conn; String answer = ""; try { if (username.equals("") || password.equals("")) throw new AuthNotProvidedException(); url = new URL(urlString); conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + getAuthentificationString()); if (postStatus) { conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream das = new DataOutputStream(conn.getOutputStream()); String content = "status=" + URLEncoder.encode(statusMessage, "UTF-8") + "&source=" + URLEncoder.encode("sametimetwitterclient", "UTF-8"); das.writeBytes(content); das.flush(); das.close(); } InputStream is = (InputStream) conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { answer += line + "\n"; } br.close(); } catch (FileNotFoundException ex) { System.out.println(ex.toString()); throw new RuntimeException("Page not Found. Maybe Twitter-API has changed."); } catch (UnknownHostException ex) { System.out.println(ex.toString()); throw new RuntimeException("Network connection problems. Could not find twitter.com"); } catch (IOException ex) { System.out.println("IO-Exception"); if (ex.getMessage().indexOf("401") > -1) { authenthicated = AUTH_BAD; throw new AuthNotAcceptedException(); } System.out.println(ex.toString()); } if (checkForError(answer) != null) { throw new RuntimeException(checkForError(answer)); } authenthicated = AUTH_OK; return answer; }
Code Sample 2:
public static String MD5Encode(String password) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } return buf.toString(); } catch (NoSuchAlgorithmException e) { return password; } }
|
00
|
Code Sample 1:
protected void processAnnotationsJndi(URL url) { try { URLConnection urlConn = url.openConnection(); DirContextURLConnection dcUrlConn; if (!(urlConn instanceof DirContextURLConnection)) { sm.getString("contextConfig.jndiUrlNotDirContextConn", url); return; } dcUrlConn = (DirContextURLConnection) urlConn; dcUrlConn.setUseCaches(false); String type = dcUrlConn.getHeaderField(ResourceAttributes.TYPE); if (ResourceAttributes.COLLECTION_TYPE.equals(type)) { Enumeration<String> dirs = dcUrlConn.list(); while (dirs.hasMoreElements()) { String dir = dirs.nextElement(); URL dirUrl = new URL(url.toString() + '/' + dir); processAnnotationsJndi(dirUrl); } } else { if (url.getPath().endsWith(".class")) { InputStream is = null; try { is = dcUrlConn.getInputStream(); processAnnotationsStream(is); } catch (IOException e) { logger.error(sm.getString("contextConfig.inputStreamJndi", url), e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } catch (IOException e) { logger.error(sm.getString("contextConfig.jndiUrl", url), e); } }
Code Sample 2:
public ImageData getJPEGDiagram() { Shell shell = new Shell(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new CsdeEditPartFactory()); viewer.setContents(getDiagram()); viewer.flush(); LayerManager lm = (LayerManager) viewer.getEditPartRegistry().get(LayerManager.ID); IFigure fig = lm.getLayer(LayerConstants.PRINTABLE_LAYERS); Dimension d = fig.getSize(); Image image = new Image(null, d.width, d.height); GC tmpGC = new GC(image); SWTGraphics graphics = new SWTGraphics(tmpGC); fig.paint(graphics); shell.dispose(); return image.getImageData(); }
|
00
|
Code Sample 1:
public static String hash(final String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return Sha1.convertToHex(sha1hash); } catch (NoSuchAlgorithmException e) { return null; } catch (UnsupportedEncodingException e) { return null; } }
Code Sample 2:
private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
|
00
|
Code Sample 1:
public static final void copyFile(File source, File target) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (java.io.IOException e) { } }
Code Sample 2:
private String getEncryptedPassword() { String encrypted; char[] pwd = password.getPassword(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(new String(pwd).getBytes("UTF-8")); byte[] digested = md.digest(); encrypted = new String(Base64Coder.encode(digested)); } catch (Exception e) { encrypted = new String(pwd); } for (int i = 0; i < pwd.length; i++) pwd[i] = 0; return encrypted; }
|
00
|
Code Sample 1:
public static void doHttpPost(String urlName, byte[] data, String contentType, String cookieData) throws InteropException { URL url = getAccessURL(urlName); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", cookieData); connection.setRequestProperty("Content-type", contentType); connection.setRequestProperty("Content-length", "" + data.length); OutputStream stream = connection.getOutputStream(); stream.write(data); stream.flush(); stream.close(); connection.connect(); InputStream inputStream = connection.getInputStream(); inputStream.close(); } catch (IOException ex) { throw new InteropException("Error POSTing to " + urlName, ex); } }
Code Sample 2:
public void download(String ftpServer, String user, String password, String fileName, File destination) throws MalformedURLException, IOException { if (ftpServer != null && fileName != null && destination != null) { StringBuffer sb = new StringBuffer("ftp://"); if (user != null && password != null) { sb.append(user); sb.append(':'); sb.append(password); sb.append('@'); } sb.append(ftpServer); sb.append('/'); sb.append(fileName); sb.append(";type=i"); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL(sb.toString()); URLConnection urlc = url.openConnection(); bis = new BufferedInputStream(urlc.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(destination)); int i; while ((i = bis.read()) != -1) { bos.write(i); } } finally { if (bis != null) try { bis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } else { System.out.println("Input not available"); } }
|
00
|
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 void write(PDDocument doc) throws COSVisitorException { document = doc; SecurityHandler securityHandler = document.getSecurityHandler(); if (securityHandler != null) { try { securityHandler.prepareDocumentForEncryption(document); this.willEncrypt = true; } catch (IOException e) { throw new COSVisitorException(e); } catch (CryptographyException e) { throw new COSVisitorException(e); } } else { this.willEncrypt = false; } COSDocument cosDoc = document.getDocument(); COSDictionary trailer = cosDoc.getTrailer(); COSArray idArray = (COSArray) trailer.getDictionaryObject("ID"); if (idArray == null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Long.toString(System.currentTimeMillis()).getBytes()); COSDictionary info = (COSDictionary) trailer.getDictionaryObject("Info"); if (info != null) { Iterator values = info.getValues().iterator(); while (values.hasNext()) { md.update(values.next().toString().getBytes()); } } idArray = new COSArray(); COSString id = new COSString(md.digest()); idArray.add(id); idArray.add(id); trailer.setItem("ID", idArray); } catch (NoSuchAlgorithmException e) { throw new COSVisitorException(e); } } cosDoc.accept(this); }
|
00
|
Code Sample 1:
private long newIndex(String indexname) { Connection con = null; ResultSet rs = null; Statement stm = null; StringBuffer sql = new StringBuffer(); indexname = indexname.trim().toUpperCase(); try { long index = -1; synchronized (FormularContextPersistensImpl.class) { con = getConnection(); stm = con.createStatement(); if ((con != null) && (stm != null)) { con.setAutoCommit(false); sql = new StringBuffer(); sql.append("SELECT * FROM INDX_EC WHERE INDX_NAME='"); sql.append(indexname); sql.append("' FOR UPDATE"); rs = stm.executeQuery(sql.toString()); if ((rs != null) && rs.next()) { sql = new StringBuffer(); index = rs.getLong("INDX_WERT") + 1; sql.append("UPDATE INDX_EC SET INDX_WERT = "); sql.append(index); sql.append(" WHERE INDX_NAME='"); sql.append(indexname); sql.append("'"); rs.close(); rs = null; if (stm.executeUpdate(sql.toString()) == 1) { con.commit(); } else { con.rollback(); index = -1; } } else { sql = new StringBuffer(); sql.append("INSERT INTO INDX_EC (INDX_NAME, INDX_WERT) VALUES('"); sql.append(indexname); sql.append("', "); sql.append(1); sql.append(")"); if (stm.executeUpdate(sql.toString()) == 1) { con.commit(); index = 1; } else { con.rollback(); } } } } return index; } catch (Exception e) { Log.getLogger().error("Error during execute SQL-Statement: " + sql.toString(), e); return -1; } finally { if (rs != null) { try { rs.close(); } catch (Exception ignore) { } } if (stm != null) { try { stm.close(); } catch (Exception ignore) { } } if (con != null) { try { con.close(); } catch (Exception ignore) { } } } }
Code Sample 2:
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; }
|
11
|
Code Sample 1:
public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; }
Code Sample 2:
public static void copyFile(File source, File target) { try { target.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }
|
00
|
Code Sample 1:
public void getFile(String url, String filepath) throws BggException { System.out.println(url); int retry = retryCount + 1; lastURL = url; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; BufferedInputStream bis = null; OutputStream osw = null; try { con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); setHeaders(con); con.setRequestMethod("GET"); responseCode = con.getResponseCode(); bis = new BufferedInputStream(con.getInputStream()); int data; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filepath)); while ((data = bis.read()) != -1) bos.write(data); bos.flush(); bos.close(); break; } finally { try { bis.close(); } catch (Exception ignore) { } try { osw.close(); } catch (Exception ignore) { } try { con.disconnect(); } catch (Exception ignore) { } } } catch (IOException ioe) { if (responseCode == UNAUTHORIZED || responseCode == FORBIDDEN) { throw new BggException(ioe.getMessage(), responseCode); } if (retriedCount == retryCount) { throw new BggException(ioe.getMessage(), responseCode); } } try { Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { } } }
Code Sample 2:
@SuppressWarnings("unchecked") private List<String> getWordList() { IConfiguration config = Configurator.getDefaultConfigurator().getConfig(CONFIG_ID); List<String> wList = (List<String>) config.getObject("word_list"); if (wList == null) { wList = new ArrayList<String>(); InputStream resrc = null; try { resrc = new URL(list_url).openStream(); } catch (Exception e) { e.printStackTrace(); } if (resrc != null) { BufferedReader br = new BufferedReader(new InputStreamReader(resrc)); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() != 0) { wList.add(line); } } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } } return wList; }
|
11
|
Code Sample 1:
boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; }
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 boolean copyFile(File destinationFolder, File fromFile) { boolean result = false; String toFileName = destinationFolder.getAbsolutePath() + "/" + fromFile.getName(); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) { try { from.close(); } catch (IOException e2) { e2.printStackTrace(); } if (to != null) { try { to.close(); result = true; } catch (IOException e3) { e3.printStackTrace(); } } } } return result; }
Code Sample 2:
private void parseTemplate(File templateFile, Map dataMap) throws ContainerException { Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(templateFile)); } catch (FileNotFoundException e) { throw new ContainerException(e); } String targetDirectoryName = args.length > 1 ? args[1] : null; if (targetDirectoryName == null) { targetDirectoryName = target; } String targetDirectory = ofbizHome + targetDirectoryName + args[0]; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { throw new ContainerException("Unable to create target directory - " + targetDirectory); } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } Writer writer = null; try { writer = new FileWriter(targetDirectory + templateFile.getName()); } catch (IOException e) { throw new ContainerException(e); } try { FreeMarkerWorker.renderTemplate(templateFile.getAbsolutePath(), reader, dataMap, writer); } catch (Exception e) { throw new ContainerException(e); } try { writer.flush(); writer.close(); } catch (IOException e) { throw new ContainerException(e); } }
|
00
|
Code Sample 1:
public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; }
Code Sample 2:
public void listgroups() throws Exception { String lapage = new String(""); Pattern pat; Matcher mat; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearAll(); System.out.print("http://groups.yahoo.com/mygroups : "); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("."); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<td class=\"grpname selected\"><a href=\"(.+?)\".*?><em>(.+?)</em></a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(mat.group(2), "", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<a href=\"(.+?)\">Next ></a>"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); System.out.println(""); }
|
11
|
Code Sample 1:
protected File compress(File orig, IWrapCompression wrapper) throws IOException { File compressed = File.createTempFile("test.", ".gz"); FileOutputStream fos = new FileOutputStream(compressed); OutputStream wos = wrapper.wrap(fos); FileInputStream fis = new FileInputStream(orig); IOUtils.copy(fis, wos); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(wos); return compressed; }
Code Sample 2:
public static void s_copy(FileInputStream fis, FileOutputStream fos) throws Exception { FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel(); in.transferTo(0, in.size(), out); if (in != null) in.close(); if (out != null) out.close(); }
|
00
|
Code Sample 1:
@Override public T[] sort(T[] values) { super.compareTimes = 0; for (int i = 0; i < values.length; i++) { for (int j = 0; j < values.length - i - 1; j++) { super.compareTimes++; if (values[j].compareTo(values[j + 1]) > 0) { T temp = values[j]; values[j] = values[j + 1]; values[j + 1] = temp; } } } return values; }
Code Sample 2:
public byte[] read(IFile input) { InputStream contents = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); contents = input.getContents(); IOUtils.copy(contents, baos); return baos.toByteArray(); } catch (IOException e) { Activator.logUnexpected(null, e); } catch (CoreException e) { Activator.logUnexpected(null, e); } finally { IOUtils.closeQuietly(contents); } return null; }
|
00
|
Code Sample 1:
public synchronized void run() { logger.info("SEARCH STARTED"); JSONObject json = null; logger.info("Opening urlConnection"); URLConnection connection = null; try { connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); } catch (IOException e) { logger.warn("PROBLEM CONTACTING GOOGLE"); e.printStackTrace(); } String line; StringBuilder builder = new StringBuilder(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } } catch (IOException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } logger.info("Google RET: " + builder.toString()); try { json = new JSONObject(builder.toString()); json.append("query", q); } catch (JSONException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } sc.onSearchFinished(json); }
Code Sample 2:
ServerInfo getServerInfo(String key, String protocol) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IOException, ClassNotFoundException, IllegalBlockSizeException, BadPaddingException { DESedeKeySpec ks = new DESedeKeySpec(Base64.decode(key)); SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede"); SecretKey sk = skf.generateSecret(ks); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, sk); ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource(protocol + ".sobj"); JarURLConnection jc = (JarURLConnection) url.openConnection(); ObjectInputStream os = new ObjectInputStream(jc.getInputStream()); SealedObject so = (SealedObject) os.readObject(); return (ServerInfo) so.getObject(cipher); }
|
11
|
Code Sample 1:
private void convertFile() { final File fileToConvert = filePanel.getInputFile(); final File convertedFile = filePanel.getOutputFile(); if (fileToConvert == null || convertedFile == null) { Main.showMessage("Select valid files for both input and output"); return; } if (fileToConvert.getName().equals(convertedFile.getName())) { Main.showMessage("Input and Output files are same.. select different files"); return; } final int len = (int) fileToConvert.length(); progressBar.setMinimum(0); progressBar.setMaximum(len); progressBar.setValue(0); try { fileCopy(fileToConvert, fileToConvert.getAbsolutePath() + ".bakup"); } catch (IOException e) { Main.showMessage("Unable to Backup input file"); return; } final BufferedReader bufferedReader; try { bufferedReader = new BufferedReader(new FileReader(fileToConvert)); } catch (FileNotFoundException e) { Main.showMessage("Unable to create reader - file not found"); return; } final BufferedWriter bufferedWriter; try { bufferedWriter = new BufferedWriter(new FileWriter(convertedFile)); } catch (IOException e) { Main.showMessage("Unable to create writer for output file"); return; } String input; try { while ((input = bufferedReader.readLine()) != null) { if (stopRequested) { break; } bufferedWriter.write(parseLine(input)); bufferedWriter.newLine(); progressBar.setValue(progressBar.getValue() + input.length()); } } catch (IOException e) { Main.showMessage("Unable to convert " + e.getMessage()); return; } finally { try { bufferedReader.close(); bufferedWriter.close(); } catch (IOException e) { Main.showMessage("Unable to close reader/writer " + e.getMessage()); return; } } if (!stopRequested) { filePanel.readOutputFile(); progressBar.setValue(progressBar.getMaximum()); Main.setStatus("Transliterate Done."); } progressBar.setValue(progressBar.getMinimum()); }
Code Sample 2:
private void appendAndDelete(FileOutputStream outstream, String file) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(file); byte[] buffer = new byte[65536]; int l; while ((l = input.read(buffer)) != -1) outstream.write(buffer, 0, l); input.close(); new File(file).delete(); }
|
11
|
Code Sample 1:
protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; }
Code Sample 2:
public static void messageDigestTest() { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("computer".getBytes()); md.update("networks".getBytes()); System.out.println(new String(md.digest())); System.out.println(new String(md.digest("computernetworks".getBytes()))); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
private static ArrayList<String> BingSearch(String query) { ArrayList<String> bingSearchResults = new ArrayList<String>(); try { String request = "http://api.bing.net/xml.aspx?AppId=731DD1E61BE6DE4601A3008DC7A0EB379149EC29" + "&Version=2.2&Market=en-US&Query=" + URLEncoder.encode("Java example for " + query, "UTF-8") + "&Sources=web+spell&Web.Count=30"; URL url = new URL(request); System.out.println("Host : " + url.getHost()); url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String finalContents = ""; while ((inputLine = reader.readLine()) != null) { finalContents += "\n" + inputLine; } Document doc = Jsoup.parse(finalContents); Elements eles = doc.getElementsByTag("web:Url"); for (Element ele : eles) { String urlText = ele.text(); if (!urlText.endsWith(".pdf") && !urlText.endsWith(".doc") && !urlText.endsWith(".ppt") && !urlText.endsWith(".PDF") && !urlText.endsWith(".DOC") && !urlText.endsWith(".PPT")) bingSearchResults.add(ele.text()); System.out.println("BingResult: " + ele.text()); } } catch (Exception e) { e.printStackTrace(); } return bingSearchResults; }
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 final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.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:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cacheName = req.getParameter("cacheName"); if (cacheName == null || cacheName.equals("")) { resp.getWriter().println("parameter cacheName required"); return; } else { StringBuffer urlStr = new StringBuffer(); urlStr.append(BASE_URL); urlStr.append("?"); urlStr.append("cacheName="); urlStr.append("rpcwc.bo.cache."); urlStr.append(cacheName); URL url = new URL(urlStr.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; StringBuffer output = new StringBuffer(); while ((line = reader.readLine()) != null) { output.append(line); output.append(System.getProperty("line.separator")); } reader.close(); resp.getWriter().println(output.toString()); } }
Code Sample 2:
public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
public static void zip(File srcDir, File destFile, FileFilter filter) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(destFile)); Collection<File> files = FileUtils.listFiles(srcDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (File f : files) { if (filter == null || filter.accept(f)) { FileInputStream in = FileUtils.openInputStream(f); out.putNextEntry(new ZipEntry(Util.relativePath(srcDir, f).replace('\\', '/'))); IOUtils.copyLarge(in, out); out.closeEntry(); IOUtils.closeQuietly(in); } } IOUtils.closeQuietly(out); } catch (Throwable t) { throw new IOException("Failed to create zip file", t); } finally { if (out != null) { out.flush(); IOUtils.closeQuietly(out); } } }
Code Sample 2:
public ManageUsers() { if (System.getProperty("user.home") != null) { dataFile = new File(System.getProperty("user.home") + File.separator + "MyRx" + File.separator + "MyRx.dat"); File dataFileDir = new File(System.getProperty("user.home") + File.separator + "MyRx"); dataFileDir.mkdirs(); } else { dataFile = new File("MyRx.dat"); } try { dataFile.createNewFile(); } catch (IOException e1) { logger.error(e1); JOptionPane.showMessageDialog(Menu.getMainMenu(), e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } File oldDataFile = new File("MyRx.dat"); if (oldDataFile.exists()) { FileChannel src = null, dst = null; try { src = new FileInputStream(oldDataFile.getAbsolutePath()).getChannel(); dst = new FileOutputStream(dataFile.getAbsolutePath()).getChannel(); dst.transferFrom(src, 0, src.size()); if (!oldDataFile.delete()) { oldDataFile.deleteOnExit(); } } catch (FileNotFoundException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { try { src.close(); dst.close(); } catch (IOException e) { logger.error(e); } } } }
|
00
|
Code Sample 1:
public static int[] sortAscending(int input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] > input[j + 1]) { int mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
Code Sample 2:
public void connect() throws IOException { if (log.isDebugEnabled()) log.debug("Connecting to: " + HOST); ftpClient.connect(HOST); if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString()); if (log.isDebugEnabled()) log.debug("Login as anonymous"); ftpClient.login("anonymous", ""); if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString()); folder = INTACT_FOLDER; }
|
11
|
Code Sample 1:
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } return convertToHex(md5hash); }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { try { setStatus(DigestSignTask.RESET, ""); if (e.getSource() == sd) if (retriveEncodedDigestFromServer()) setStatus(DigestSignTask.RESET, "Inserire il pin e battere INVIO per firmare."); if (e.getSource() == pwd) { initStatus(0, DigestSignTask.SIGN_MAXIMUM); if (detectCardAndCriptoki()) { dsTask = new DigestSignTask(getCryptokiLib(), getSignerLabel(), log); timer = new Timer(ONE_SECOND, new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { setStatus(dsTask.getCurrent(), dsTask.getMessage()); if (dsTask.done()) { timer.stop(); progressBar.setValue(progressBar.getMinimum()); if (dsTask.getCurrent() == DigestSignTask.SIGN_DONE) { Toolkit.getDefaultToolkit().beep(); setEncryptedDigest(dsTask.getEncryptedDigest()); returnEncryptedDigestToForm(); setCertificate(dsTask.getCertificate()); returnCertificateToForm(); if (getSubmitAfterSigning()) { submitForm(); } } enableControls(true); } } }); sign(); } } if (e.getSource() == enc) { log.println("\nCalculating digest ...\n"); java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5"); md5.update(dataArea.getText().getBytes("UTF8")); byte[] digest = md5.digest(); log.println("digest:\n" + formatAsHexString(digest)); log.println("Done."); setEncodedDigest(encodeFromBytes(digest)); returnDigestToForm(); } if (e.getSource() == ld) retriveEncodedDigestFromForm(); if (e.getSource() == led) retriveEncryptedDigestFromForm(); if (e.getSource() == v) { verify(); } } catch (Exception ex) { log.println(ex.toString()); } finally { pwd.setText(""); } }
|
00
|
Code Sample 1:
private static void main(String mp3Path) throws IOException { String convPath = "http://android.adinterest.biz/wav2mp3.php?k="; String uri = convPath + mp3Path; URL rssurl = new URL(uri); InputStream is = rssurl.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String buf = ""; while ((buf = br.readLine()) != null) { } is.close(); br.close(); }
Code Sample 2:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { log.fatal("not a http request"); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int pathStartIdx = 0; String resourceName = null; pathStartIdx = uri.indexOf(path); if (pathStartIdx <= -1) { log.fatal("the url pattern must match: " + path + " found uri: " + uri); return; } resourceName = uri.substring(pathStartIdx + path.length()); int suffixIdx = uri.lastIndexOf('.'); if (suffixIdx <= -1) { log.fatal("no file suffix found for resource: " + uri); return; } String suffix = uri.substring(suffixIdx + 1).toLowerCase(); String mimeType = (String) mimeTypes.get(suffix); if (mimeType == null) { log.fatal("no mimeType found for resource: " + uri); log.fatal("valid mimeTypes are: " + mimeTypes.keySet()); return; } String themeName = getThemeName(); if (themeName == null) { themeName = this.themeName; } if (!themeName.startsWith("/")) { themeName = "/" + themeName; } InputStream is = null; is = ResourceFilter.class.getResourceAsStream(themeName + resourceName); if (is != null) { IOUtils.copy(is, response.getOutputStream()); response.setContentType(mimeType); response.flushBuffer(); IOUtils.closeQuietly(response.getOutputStream()); IOUtils.closeQuietly(is); } else { log.fatal("error loading resource: " + resourceName); } }
|
00
|
Code Sample 1:
public void run() { String s; s = ""; try { URL url = new URL("http://www.askoxford.com/concise_oed/" + word.toLowerCase() + "?view=uk"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("<h2>" + word.toLowerCase() + "(.+?)<p><a href", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } button.setEnabled(true); }
Code Sample 2:
public List<String[]> getCSV(String name) { return new ResourceLoader<List<String[]>>(name) { @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } } }.get(); }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } }
|
00
|
Code Sample 1:
private String getMAC(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
private static ArrayList<String> BingSearch(String query) { ArrayList<String> bingSearchResults = new ArrayList<String>(); try { String request = "http://api.bing.net/xml.aspx?AppId=731DD1E61BE6DE4601A3008DC7A0EB379149EC29" + "&Version=2.2&Market=en-US&Query=" + URLEncoder.encode("Java example for " + query, "UTF-8") + "&Sources=web+spell&Web.Count=30"; URL url = new URL(request); System.out.println("Host : " + url.getHost()); url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String finalContents = ""; while ((inputLine = reader.readLine()) != null) { finalContents += "\n" + inputLine; } Document doc = Jsoup.parse(finalContents); Elements eles = doc.getElementsByTag("web:Url"); for (Element ele : eles) { String urlText = ele.text(); if (!urlText.endsWith(".pdf") && !urlText.endsWith(".doc") && !urlText.endsWith(".ppt") && !urlText.endsWith(".PDF") && !urlText.endsWith(".DOC") && !urlText.endsWith(".PPT")) bingSearchResults.add(ele.text()); System.out.println("BingResult: " + ele.text()); } } catch (Exception e) { e.printStackTrace(); } return bingSearchResults; }
|
00
|
Code Sample 1:
private String doRawGet(URI uri) throws XdsInternalException { HttpURLConnection conn = null; String response = null; try { URL url; try { url = uri.toURL(); } catch (Exception e) { throw HttpClient.getException(e, uri.toString()); } HttpsURLConnection.setDefaultHostnameVerifier(this); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/html, text/xml, text/plain, */*"); conn.connect(); response = this.getResponse(conn); } catch (IOException e) { throw HttpClient.getException(e, uri.toString()); } finally { if (conn != null) { conn.disconnect(); } } return response; }
Code Sample 2:
public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { for (int i = 0; i < args.length - 2; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > (i + 1)) i = CommonParameters.startArg - 1; } if (args.length < CommonParameters.startArg + 2) { u.usage(); System.exit(1); } try { int readsize = 1024; ContentName argName = ContentName.fromURI(args[CommonParameters.startArg]); CCNHandle handle = CCNHandle.open(); File theFile = new File(args[CommonParameters.startArg + 1]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(argName, handle); else input = new CCNFileInputStream(argName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public void doRecurringPayment(Subscription subscription) { int amount = Math.round(subscription.getTotalCostWithDiscounts() * 100.0f); String currency = subscription.getCurrency(); String aliasCC = subscription.getAliasCC(); String expm = subscription.getLastCardExpm(); String expy = subscription.getLastCardExpy(); String subscriptionId = String.valueOf(subscription.getSubscriptionId()); StringBuffer xmlSB = new StringBuffer(""); xmlSB.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); xmlSB.append("<authorizationService version=\"1\">\n"); xmlSB.append(" <body merchantId=\"" + getMerchantId() + "\" testOnly=\"" + getTestOnly() + "\">\n"); xmlSB.append(" <transaction refno=\"" + REF_NO + "\">\n"); xmlSB.append(" <request>\n"); xmlSB.append(" <amount>" + amount + "</amount>\n"); xmlSB.append(" <currency>" + currency + "</currency>\n"); xmlSB.append(" <aliasCC>" + aliasCC + "</aliasCC>\n"); xmlSB.append(" <expm>" + expm + "</expm>\n"); xmlSB.append(" <expy>" + expy + "</expy>\n"); xmlSB.append(" <subscriptionId>" + subscriptionId + "</subscriptionId>\n"); xmlSB.append(" </request>\n"); xmlSB.append(" </transaction>\n"); xmlSB.append(" </body>\n"); xmlSB.append("</authorizationService>\n"); String xmlS = xmlSB.toString(); try { java.net.URL murl = new java.net.URL(getRecurringPaymentUrl()); java.net.HttpURLConnection mcon = (java.net.HttpURLConnection) murl.openConnection(); mcon.setRequestMethod("POST"); mcon.setRequestProperty("encoding", "UTF-8"); mcon.setRequestProperty("Content-Type", "text/xml"); mcon.setRequestProperty("Content-length", String.valueOf(xmlS.length())); mcon.setDoOutput(true); java.io.OutputStream outs = mcon.getOutputStream(); outs.write(xmlS.getBytes("UTF-8")); outs.close(); java.io.BufferedReader inps = new java.io.BufferedReader(new java.io.InputStreamReader(mcon.getInputStream())); StringBuffer respSB = new StringBuffer(""); String s = null; while ((s = inps.readLine()) != null) { respSB.append(s); } inps.close(); String respXML = respSB.toString(); processReccurentPaymentResponce(respXML); } catch (Exception ex) { throw new SecurusException(ex); } }
Code Sample 2:
public static void writeFromURL(String urlstr, String filename) throws Exception { URL url = new URL(urlstr); InputStream in = url.openStream(); BufferedReader bf = null; StringBuffer sb = new StringBuffer(); try { bf = new BufferedReader(new InputStreamReader(in, "latin1")); String s; while (true) { s = bf.readLine(); if (s != null) { sb.append(s); } else { break; } } } catch (Exception e) { throw e; } finally { bf.close(); } writeRawBytes(sb.toString(), filename); }
|
11
|
Code Sample 1:
public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
Code Sample 2:
public static void copyFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; File resourceFile = new File(resourceFileName); if (!resourceFile.isFile()) { System.out.println(resourceFileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
|
00
|
Code Sample 1:
private String encode(String arg) { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(arg.getBytes()); byte[] md5sum = digest.digest(); final BigInteger bigInt = new BigInteger(1, md5sum); final String output = bigInt.toString(16); return output; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 required: " + e.getMessage(), e); } }
Code Sample 2:
private String readJsonString() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER_URL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TAG, "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
|
00
|
Code Sample 1:
public MapInfo loadLocalMapData(String fileName) { MapInfo info = mapCacheLocal.get(fileName); if (info != null && info.getContent() == null) { try { BufferedReader bufferedreader; URL fetchUrl = new URL(localMapContextUrl, fileName); URLConnection urlconnection = fetchUrl.openConnection(); if (urlconnection.getContentEncoding() != null) { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding())); } else { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8")); } String line; StringBuilder mapContent = new StringBuilder(); while ((line = bufferedreader.readLine()) != null) { mapContent.append(line); mapContent.append("\n"); } info.setContent(mapContent.toString()); GameMapImplementation gameMap = GameMapImplementation.createFromMapInfo(info); } catch (IOException _ex) { System.err.println("HexTD::readFile:: Can't read from " + fileName); } } else { System.err.println("HexTD::readFile:: file not in cache: " + fileName); } return info; }
Code Sample 2:
void copyFile(String from, String to) throws IOException { File destFile = new File(to); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(from).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
Code Sample 2:
public static JSONObject delete(String uid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(DELETE_URI + "?uid=" + uid); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
|
11
|
Code Sample 1:
public Writer createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new OutputStreamWriter(zos, "UTF-8"); }
Code Sample 2:
private void parseExternalCss(Document d) throws XPathExpressionException, IOException { InputStream is = null; try { XPath xp = xpf.newXPath(); XPathExpression xpe = xp.compile("//link[@type='text/css']/@href"); NodeList nl = (NodeList) xpe.evaluate(d, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Attr a = (Attr) nl.item(i); String url = a.getValue(); URL u = new URL(url); is = new BufferedInputStream(u.openStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); parser.add(new String(baos.toByteArray(), "UTF-8")); Element linkNode = a.getOwnerElement(); Element parent = (Element) linkNode.getParentNode(); parent.removeChild(linkNode); IOUtils.closeQuietly(is); is = null; } } finally { IOUtils.closeQuietly(is); } }
|
00
|
Code Sample 1:
public List<String> query(String query) throws IOException { List<String> list = new LinkedList<String>(); query = URLEncoder.encode(query, "UTF-8"); String queryurl = baseurl + "?type=tuples&lang=itql&format=csv&query=" + query; URL url = new URL(queryurl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); while (line != null) { list.add(line); line = reader.readLine(); } reader.close(); return list; }
Code Sample 2:
public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
|
00
|
Code Sample 1:
private void validate(String id, WriteToWebServerFile writeFile, char[][] charData) throws Exception { for (int i = 0; i < charData.length; i++) { assertTrue("There is a URL for input " + i, writeFile.hasNextURL()); URL url = writeFile.nextURL(); String path = url.getPath(); assertTrue("URL " + url + " contains request resource ID", path.indexOf(id) != -1); URLConnection connection = url.openConnection(); Reader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); int value; int index = 0; while (((value = reader.read()) != -1) && (index < charData[i].length)) { assertEquals("Character data " + i + " : " + index, (int) charData[i][index], value); index++; } } }
Code Sample 2:
@SuppressWarnings("unchecked") private List<String> getWordList() { IConfiguration config = Configurator.getDefaultConfigurator().getConfig(CONFIG_ID); List<String> wList = (List<String>) config.getObject("word_list"); if (wList == null) { wList = new ArrayList<String>(); InputStream resrc = null; try { resrc = new URL(list_url).openStream(); } catch (Exception e) { e.printStackTrace(); } if (resrc != null) { BufferedReader br = new BufferedReader(new InputStreamReader(resrc)); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() != 0) { wList.add(line); } } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } } return wList; }
|
00
|
Code Sample 1:
@Override protected Object doInBackground() throws Exception { ArchiveInputStream bufIn = null; FileOutputStream fileOut = null; try { bufIn = DecompressionWorker.guessStream(fileToExtract); ArchiveEntry curZip = null; int progress = 0; while ((curZip = bufIn.getNextEntry()) != null) { if (!curZip.isDirectory()) { byte[] content = new byte[(int) curZip.getSize()]; fileOut = new FileOutputStream(extractionFile.getAbsolutePath() + File.separator + curZip.getName()); for (int i = 0; i < content.length; i++) { fileOut.write(content[i]); } publish(new Integer(progress)); progress++; } } } finally { if (bufIn != null) { bufIn.close(); } } return null; }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
public static void copyFile(File file, String destDir) throws IOException { if (!isCanReadFile(file)) throw new RuntimeException("The File can't read:" + file.getPath()); if (!isCanWriteDirectory(destDir)) throw new RuntimeException("The Directory can't write:" + destDir); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(file).getChannel(); dstChannel = new FileOutputStream(destDir + "/" + file.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { throw e; } finally { if (srcChannel != null) try { srcChannel.close(); } catch (IOException e) { } if (dstChannel != null) try { dstChannel.close(); } catch (IOException e) { } } }
Code Sample 2:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
|
11
|
Code Sample 1:
public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } }
Code Sample 2:
JcrFile createBody(Part part) throws IOException, MessagingException { JcrFile body = new JcrFile(); body.setName("part"); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); body.setMimeType(part.getContentType()); body.setLastModified(java.util.Calendar.getInstance()); return body; }
|
00
|
Code Sample 1:
public void moveRuleDown(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt, language, tag); if ((row < 1) || (row > (max - 1))) throw new IllegalArgumentException("Row number (" + row + ") was not between 1 and " + (max - 1)); stmt.executeUpdate("update LanguageMorphologies set Rank = -1 " + "where Rank = " + row + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + row + "where Rank = " + (row + 1) + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + (row + 1) + "where Rank = -1 and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); 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:
void readData() { String[] nextLine; int line; double value; URL url = null; String FileToRead; try { for (int i = 0; i < names.length; i++) { FileToRead = "data/" + names[i] + ".csv"; url = new URL(ja.getCodeBase(), FileToRead); System.out.println(url.toString()); InputStream in = url.openStream(); CSVReader reader = new CSVReader(new InputStreamReader(in)); line = 0; while ((nextLine = reader.readNext()) != null) { allset.months[line] = Integer.parseInt(nextLine[0].substring(0, 2)); allset.years[line] = Integer.parseInt(nextLine[0].substring(6, 10)); value = Double.parseDouble(nextLine[1]); allset.values.getDataRef()[line][i] = value; line++; } } } catch (IOException e) { System.err.println("File Read Exception"); } }
|
00
|
Code Sample 1:
@Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
@Override public void run() { while (run) { try { URL url = new URL("http://" + server.getIp() + "/" + tomcat.getName() + "/ui/pva/version.jsp?RT=" + System.currentTimeMillis()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("UTF-8"))); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("currentversion")) { String s = inputLine.substring(inputLine.indexOf("=") + 1, inputLine.length()); tomcat.setDetailInfo(s.trim()); } } in.close(); tomcat.setIsAlive(true); } catch (Exception e) { tomcat.setIsAlive(false); } try { Thread.sleep(60000); } catch (InterruptedException e) { } } }
|
00
|
Code Sample 1:
void readFileHeader(DmgConfigDMO config, ConfigLocation sl) throws IOException { fileHeader = ""; if (config.getGeneratedFileHeader() != null) { StringBuffer sb = new StringBuffer(); if (sl.getJarFilename() != null) { URL url = new URL("jar:file:" + sl.getJarFilename() + "!/" + sl.getJarDirectory() + "/" + config.getGeneratedFileHeader()); LineNumberReader in = new LineNumberReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { sb.append(str + "\n"); } in.close(); } else { LineNumberReader in = new LineNumberReader(new FileReader(sl.getDirectory() + File.separator + config.getGeneratedFileHeader())); String str; while ((str = in.readLine()) != null) { sb.append(str + "\n"); } in.close(); } fileHeader = sb.toString(); } }
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:
public void execute(HttpResponse response) throws HttpException, IOException { Collection<Data> allData = internalDataBank.getAll(); StringBuffer content = new StringBuffer(); for (Data data : allData) { content.append("keyHash:").append(data.getKeyHash()).append(", "); content.append("version:").append(data.getVersion()).append(", "); content.append("size:").append(data.getContent().length); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); }
Code Sample 2:
public ResourceBundle getResources() { if (resources == null) { String lang = userProps.getProperty("language"); lang = "en"; try { URL myurl = getResource("Resources_" + lang.trim() + ".properties"); InputStream in = myurl.openStream(); resources = new PropertyResourceBundle(in); in.close(); } catch (Exception ex) { System.err.println("Error loading Resources"); return null; } } return resources; }
|
11
|
Code Sample 1:
public File getFile(String file) { DirProperties dp; List files = new ArrayList(); for (int i = 0; i < locs.size(); i++) { dp = (DirProperties) locs.get(i); if (dp.isReadable()) { File g = new File(dp.getLocation() + slash() + file); if (g.exists()) files.add(g); } } if (files.size() == 0) { throw new UnsupportedOperationException("at least one DirProperty should get 'read=true'"); } else if (files.size() == 1) { return (File) files.get(0); } else { File fromFile = (File) files.get(files.size() - 2); File toFile = (File) files.get(files.size() - 1); byte reading[] = new byte[2024]; try { FileInputStream stream = new FileInputStream(fromFile); FileOutputStream outStr = new FileOutputStream(toFile); while (stream.read(reading) != -1) { outStr.write(reading); } } catch (FileNotFoundException ex) { getLogger().severe("FileNotFound: while copying from " + fromFile + " to " + toFile); } catch (IOException ex) { getLogger().severe("IOException: while copying from " + fromFile + " to " + toFile); } return toFile; } }
Code Sample 2:
public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req, ActionResponse res) throws Exception { boolean editor = false; req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, false); User user = _getUser(req); List<Role> roles = RoleFactory.getAllRolesForUser(user.getUserId()); for (Role role : roles) { if (role.getName().equals("Report Administrator") || role.getName().equals("Report Editor") || role.getName().equals("CMS Administrator")) { req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, true); editor = true; break; } } requiresInput = false; badParameters = false; newReport = false; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); String cmd = req.getParameter(Constants.CMD); Logger.debug(this, "Inside EditReportAction cmd=" + cmd); ReportForm rfm = (ReportForm) form; ArrayList<String> ds = (DbConnectionFactory.getAllDataSources()); ArrayList<DataSource> dsResults = new ArrayList<DataSource>(); for (String dataSource : ds) { DataSource d = rfm.getNewDataSource(); if (dataSource.equals(com.dotmarketing.util.Constants.DATABASE_DEFAULT_DATASOURCE)) { d.setDsName("DotCMS Datasource"); } else { d.setDsName(dataSource); } dsResults.add(d); } rfm.setDataSources(dsResults); httpReq.setAttribute("dataSources", rfm.getDataSources()); Long reportId = UtilMethods.parseLong(req.getParameter("reportId"), 0); String referrer = req.getParameter("referrer"); if (reportId > 0) { report = ReportFactory.getReport(reportId); ArrayList<String> adminRoles = new ArrayList<String>(); adminRoles.add(com.dotmarketing.util.Constants.ROLE_REPORT_ADMINISTRATOR); if (user.getUserId().equals(report.getOwner())) { _checkWritePermissions(report, user, httpReq, adminRoles); } if (cmd == null || !cmd.equals(Constants.EDIT)) { rfm.setSelectedDataSource(report.getDs()); rfm.setReportName(report.getReportName()); rfm.setReportDescription(report.getReportDescription()); rfm.setReportId(report.getInode()); rfm.setWebFormReport(report.isWebFormReport()); httpReq.setAttribute("selectedDS", report.getDs()); } } else { if (!editor) { throw new DotRuntimeException("user not allowed to create a new report"); } report = new Report(); report.setOwner(_getUser(req).getUserId()); newReport = true; } req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, report); if ((cmd != null) && cmd.equals(Constants.EDIT)) { if (Validator.validate(req, form, mapping)) { report.setReportName(rfm.getReportName()); report.setReportDescription(rfm.getReportDescription()); report.setWebFormReport(rfm.isWebFormReport()); if (rfm.isWebFormReport()) report.setDs("None"); else report.setDs(rfm.getSelectedDataSource()); String jrxmlPath = ""; String jasperPath = ""; try { HibernateUtil.startTransaction(); ReportFactory.saveReport(report); _applyPermissions(req, report); if (!rfm.isWebFormReport()) { if (UtilMethods.isSet(Config.getStringProperty("ASSET_REAL_PATH"))) { jrxmlPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"; jasperPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"; } else { jrxmlPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"); jasperPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"); } UploadPortletRequest upr = PortalUtil.getUploadPortletRequest(req); File importFile = upr.getFile("jrxmlFile"); if (importFile.exists()) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(importFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); File f = new File(jrxmlPath); FileChannel channelTo = new FileOutputStream(f).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); try { JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath); } catch (Exception e) { Logger.error(this, "Unable to compile or save jrxml: " + e.toString()); try { f = new File(jrxmlPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jrxml. This is usually a permissions problem."); } try { f = new File(jasperPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jasper. This is usually a permissions problem."); } HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", UtilMethods.htmlLineBreak(e.getMessage())); setForward(req, "portlet.ext.report.edit_report"); return; } JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath); ReportParameterFactory.deleteReportsParameters(report); _loadReportParameters(jasperReport.getParameters()); report.setRequiresInput(requiresInput); HibernateUtil.save(report); } else if (newReport) { HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", "message.report.compile.error"); setForward(req, "portlet.ext.report.edit_report"); return; } } HibernateUtil.commitTransaction(); HashMap params = new HashMap(); SessionMessages.add(req, "message", "message.report.upload.success"); params.put("struts_action", new String[] { "/ext/report/view_reports" }); referrer = com.dotmarketing.util.PortletURLUtil.getRenderURL(((ActionRequestImpl) req).getHttpServletRequest(), javax.portlet.WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, referrer); return; } catch (Exception ex) { HibernateUtil.rollbackTransaction(); Logger.error(this, "Unable to save Report: " + ex.toString()); File f; Logger.info(this, "Trying to delete jrxml"); try { f = new File(jrxmlPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jrxml. This is usually because the file doesn't exist."); } try { f = new File(jasperPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jasper. This is usually because the file doesn't exist."); } if (badParameters) { SessionMessages.add(req, "error", ex.getMessage()); } else { SessionMessages.add(req, "error", "message.report.compile.error"); } setForward(req, "portlet.ext.report.edit_report"); return; } } else { setForward(req, "portlet.ext.report.edit_report"); } } if ((cmd != null) && cmd.equals("downloadReportSource")) { ActionResponseImpl resImpl = (ActionResponseImpl) res; HttpServletResponse response = resImpl.getHttpServletResponse(); if (!downloadSourceReport(reportId, httpReq, response)) { SessionMessages.add(req, "error", "message.report.source.file.not.found"); } } setForward(req, "portlet.ext.report.edit_report"); }
|
11
|
Code Sample 1:
private String endcodePassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); Base64 base64 = new Base64(); String hash = new String(base64.encode(raw)); return hash; }
Code Sample 2:
private boolean verifyPassword(String password, byte[] hash) { boolean returnValue = false; try { MessageDigest msgDigest = MessageDigest.getInstance("SHA-1"); msgDigest.update(password.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); returnValue = Arrays.equals(hash, digest); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } return returnValue; }
|
11
|
Code Sample 1:
public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); }
Code Sample 2:
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
|
11
|
Code Sample 1:
public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); }
Code Sample 2:
public StringBuffer render(RenderEngine c) { String logTime = null; if (c.getWorkerContext() != null) { logTime = c.getWorkerContext().getWorkerStart(); } if (c.isBreakState() || !c.canRender("u")) { return new StringBuffer(); } StringBuffer buffer = new StringBuffer(); varname = TagInspector.processElement(varname, c); action = TagInspector.processElement(action, c); filemode = TagInspector.processElement(filemode, c); xmlparse = TagInspector.processElement(xmlparse, c); encoding = TagInspector.processElement(encoding, c); decoding = TagInspector.processElement(decoding, c); filter = TagInspector.processElement(filter, c); sort = TagInspector.processElement(sort, c); useDocroot = TagInspector.processElement(useDocroot, c); useFilename = TagInspector.processElement(useFilename, c); useDest = TagInspector.processElement(useDest, c); xmlOutput = TagInspector.processElement(xmlOutput, c); renderOutput = TagInspector.processElement(renderOutput, c); callProc = TagInspector.processElement(callProc, c); vartype = TagInspector.processElement(vartype, c); if (sort == null || sort.equals("")) { sort = "asc"; } if (useFilename.equals("") && !action.equalsIgnoreCase("listing")) { return new StringBuffer(); } boolean isRooted = true; if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; } } if (isRooted && (useFilename.indexOf("/") == -1 || useFilename.startsWith("./"))) { if (c.getWorkerContext() != null && useFilename.startsWith("./")) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename.substring(2); Debug.inform("CWD path specified in filename, rewritten to '" + useFilename + "'"); } else if (c.getWorkerContext() != null && useFilename.indexOf("/") == -1) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename; Debug.inform("No path specified in filename, rewritten to '" + useFilename + "'"); } else { Debug.inform("No path specified in filename, no worker context, not rewriting filename."); } } StringBuffer filenameData = null; StringBuffer contentsData = null; StringBuffer fileDestData = null; contentsData = TagInspector.processBody(this, c); filenameData = new StringBuffer(useFilename); fileDestData = new StringBuffer(useDest); String currentDocroot = null; if (c.getWorkerContext() == null) { if (c.getRenderContext().getCurrentDocroot() == null) { currentDocroot = "."; } else { currentDocroot = c.getRenderContext().getCurrentDocroot(); } } else { currentDocroot = c.getWorkerContext().getDocRoot(); } if (!isRooted) { currentDocroot = ""; } if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; currentDocroot = ""; } } if (!currentDocroot.endsWith("/")) { if (!currentDocroot.equals("") && currentDocroot.length() > 0) { currentDocroot += "/"; } } if (filenameData != null) { filenameData = new StringBuffer(filenameData.toString().replaceAll("\\.\\.", "")); } if (fileDestData != null) { fileDestData = new StringBuffer(fileDestData.toString().replaceAll("\\.\\.", "")); } if (action.equalsIgnoreCase("read")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileInputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte data[] = null; boolean vfsLoaded = false; try { data = c.getVendContext().getFileAccess().getFile(c.getWorkerContext(), filenameData.toString().replaceAll("\\.\\.", ""), c.getClientContext().getMatchedHost(), c.getVendContext().getVend().getRenderExtension(c.getClientContext().getMatchedHost()), null); bos.write(data, 0, data.length); vfsLoaded = true; } catch (Exception e) { Debug.user(logTime, "Included file attempt with VFS of file '" + filenameData + "' failed: " + e); } if (data == null) { try { is = new FileInputStream(file); } catch (Exception e) { Debug.user(logTime, "Unable to render: Filename '" + currentDocroot + filenameData + "' does not exist."); return new StringBuffer(); } } if (xmlparse == null || xmlparse.equals("")) { if (data == null) { Debug.user(logTime, "Opening filename '" + currentDocroot + filenameData + "' for reading into buffer '" + varname + "'"); data = new byte[32768]; int totalBytesRead = 0; while (true) { int bytesRead; try { bytesRead = is.read(data); bos.write(data, 0, bytesRead); } catch (Exception e) { break; } if (bytesRead <= 0) { break; } totalBytesRead += bytesRead; } } byte docOutput[] = bos.toByteArray(); if (renderOutput != null && renderOutput.equalsIgnoreCase("ssp")) { String outputData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n" + new String(FileAccess.getDefault().processServerPageData(c.getWorkerContext(), docOutput)); docOutput = outputData.getBytes(); } Debug.user(logTime, "File read complete: " + docOutput.length + " byte(s)"); if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (encoding != null && encoding.equalsIgnoreCase("url")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.URLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.URLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("xml")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.XMLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.XMLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("base64")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Base64.encode(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Base64.encode(docOutput)); } } else if (encoding != null && (encoding.equalsIgnoreCase("javascript") || encoding.equalsIgnoreCase("js"))) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.JavascriptEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.JavascriptEncode(new String(docOutput))); } } else { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, new String(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(new String(docOutput)); } } } else { RenderEngine engine = new RenderEngine(null); DocumentEngine docEngine = null; try { if (vfsLoaded) { ByteArrayInputStream bais = new ByteArrayInputStream(data); docEngine = new DocumentEngine(bais); } else { docEngine = new DocumentEngine(is); } } catch (Exception e) { c.setExceptionState(true, "XML parse of data read from file failed: " + e.getMessage()); } engine.setDocumentEngine(docEngine); c.addNodeSet(varname, docEngine.rootTag.thisNode); } if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); } else if (action.equalsIgnoreCase("write")) { try { String rootDir = filenameData.toString(); if (rootDir.lastIndexOf("/") != -1 && rootDir.lastIndexOf("/") != 0) { rootDir = rootDir.substring(0, rootDir.lastIndexOf("/")); java.io.File mkdirFile = new java.io.File(currentDocroot + rootDir); if (!mkdirFile.mkdirs()) { Debug.inform("Unable to create directory '" + currentDocroot + rootDir + "'"); } else { Debug.inform("Created directory '" + currentDocroot + rootDir + "'"); } } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileOutputStream fos = null; if (file == null) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Cannot write to location specified"); return new StringBuffer(); } else if (file.isDirectory()) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Is a directory."); return new StringBuffer(); } if (filemode.equalsIgnoreCase("append")) { fos = new FileOutputStream(file, true); } else { fos = new FileOutputStream(file, false); } if (decoding != null && !decoding.equals("")) { if (decoding.equalsIgnoreCase("base64")) { try { byte contentsDecoded[] = Base64.decode(contentsData.toString().getBytes()); fos.write(contentsDecoded); } catch (Exception e) { c.setExceptionState(true, "Encoded data in <content> element does not contain valid Base64-" + "encoded data."); } } else { fos.write(contentsData.toString().getBytes()); } } else { fos.write(contentsData.toString().getBytes()); } try { fos.flush(); } catch (IOException e) { Debug.inform("Unable to flush output data: " + e.getMessage()); } fos.close(); Debug.user(logTime, "Wrote contents to filename '" + currentDocroot + filenameData + "' (length=" + contentsData.length() + ")"); } catch (IOException e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } catch (Exception e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } } else if (action.equalsIgnoreCase("listing")) { String filenameDataString = filenameData.toString(); if (filenameDataString.equals("")) { filenameDataString = c.getClientContext().getPostVariable("current_path"); } if (filenameDataString == null) { c.setExceptionState(true, "Filename cannot be blank when listing."); return new StringBuffer(); } while (filenameDataString.endsWith("/")) { filenameDataString = filenameDataString.substring(0, filenameDataString.length() - 1); } Vector fileList = new Vector(); java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String curDirname = filenameData.toString(); String parentDirectory = null; String[] dirEntries = curDirname.split("/"); int numSlashes = 0; for (int i = 0; i < curDirname.length(); i++) { if (curDirname.toString().charAt(i) == '/') { numSlashes++; } } parentDirectory = "/"; if (numSlashes > 1) { for (int i = 0; i < (dirEntries.length - 1); i++) { if (dirEntries[i] != null && !dirEntries[i].equals("")) { parentDirectory += dirEntries[i] + "/"; } } } if (parentDirectory.length() > 1 && parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_JAR) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); int depth = 0; for (int i = 0; i < filenameData.toString().length(); i++) { if (filenameData.toString().charAt(i) == '/') { depth++; } } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(list, new ZipSorterAscending()); } else { Arrays.sort(list, new ZipSorterDescending()); } for (int i = 0; i < list.length; i++) { ZipEntry zEntry = (ZipEntry) list[i]; String zipFile = filenameData.toString() + "/" + zEntry.getName(); String displayFilename = zipFile.replaceFirst(filenameData.toString(), ""); int curDepth = 0; if (zipFile.equalsIgnoreCase(".acl") || zipFile.equalsIgnoreCase("access.list") || zipFile.equalsIgnoreCase("application.inc") || zipFile.equalsIgnoreCase("global.inc") || zipFile.indexOf("/.proc") != -1 || zipFile.indexOf("/procedures") != -1) { continue; } for (int x = 0; x < displayFilename.length(); x++) { if (displayFilename.charAt(x) == '/') { curDepth++; } } if (zipFile.startsWith(filenameData.toString())) { String fileLength = "" + zEntry.getSize(); String fileType = "file"; if (curDepth == depth) { if (zEntry.isDirectory()) { fileType = "directory"; } else { fileType = "file"; } String fileMode = "read-only"; String fileTime = Long.toString(zEntry.getTime()); buffer.append(" <file name=\""); buffer.append(displayFilename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(time)", false, fileTime); } } else { if (curDepth == depth) { fileList.add(zipFile); } } } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_FS) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); java.io.File[] filesorted = new java.io.File[list.length]; for (int i = 0; i < list.length; i++) { filesorted[i] = (java.io.File) list[i]; } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(filesorted, new FileSorterAscending()); } else { Arrays.sort(filesorted, new FileSorterDescending()); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < filesorted.length; i++) { java.io.File zEntry = filesorted[i]; String filename = filenameData.toString() + "/" + zEntry.getName(); if (filename.equalsIgnoreCase(".acl") || filename.equalsIgnoreCase("access.list") || filename.equalsIgnoreCase("application.inc") || filename.equalsIgnoreCase("global.inc") || filename.indexOf("/.proc") != -1 || filename.indexOf("/procedures") != -1) { continue; } String displayFilename = filename.replaceFirst(filenameData.toString(), ""); String fileLength = "" + zEntry.length(); String fileType = "file"; if (zEntry.isDirectory()) { fileType = "directory"; } else if (zEntry.isFile()) { fileType = "file"; } else if (zEntry.isHidden()) { fileType = "hidden"; } else if (zEntry.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (zEntry.canRead() && !zEntry.canWrite()) { fileMode = "read-only"; } else if (!zEntry.canRead() && zEntry.canWrite()) { fileMode = "write-only"; } else if (zEntry.canRead() && zEntry.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(zEntry.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(filename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(zEntry); } c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else { String[] fileStringList = null; if (!filter.equals("")) { fileStringList = file.list(new ListFilter(filter)); } else { fileStringList = file.list(); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(fileStringList, new StringSorterAscending()); } else { Arrays.sort(fileStringList, new StringSorterDescending()); } if (fileStringList == null) { buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); } else { c.getVariableContainer().setVector(varname, fileList); } return new StringBuffer(); } else { Debug.user(logTime, "Directory '" + currentDocroot + filenameData + "' returns " + fileStringList.length + " entry(ies)"); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < fileStringList.length; i++) { file = new java.io.File(currentDocroot + filenameData.toString() + "/" + fileStringList[i]); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } else if (file.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(fileStringList[i]); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(fileStringList[i]); } c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } } else if (action.equalsIgnoreCase("delete")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.isDirectory()) { boolean success = deleteDir(new java.io.File(currentDocroot + filenameData.toString())); if (!success) { c.setExceptionState(true, "Unable to delete '" + currentDocroot + filenameData + "'"); } } else { String filenamePattern = null; if (filenameData.toString().indexOf("/") != -1) { filenamePattern = filenameData.toString().substring(filenameData.toString().lastIndexOf("/") + 1); } String filenameDirectory = currentDocroot; if (filenameData.toString().indexOf("/") != -1) { filenameDirectory += filenameData.substring(0, filenameData.toString().lastIndexOf("/")); } String[] fileStringList = null; file = new java.io.File(filenameDirectory); fileStringList = file.list(new ListFilter(filenamePattern)); for (int i = 0; i < fileStringList.length; i++) { (new java.io.File(filenameDirectory + "/" + fileStringList[i])).delete(); } } } else if (action.equalsIgnoreCase("rename") || action.equalsIgnoreCase("move")) { if (fileDestData.equals("")) { c.getVariableContainer().setVariable(varname + "-result", filenameData + ": File operation failed: No destination filename given."); return new StringBuffer(); } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); boolean success = file.renameTo(new java.io.File(currentDocroot + fileDestData.toString(), file.getName())); if (!success) { c.setExceptionState(true, "Unable to rename '" + currentDocroot + filenameData + "' to '" + currentDocroot + fileDestData + "'"); } } else if (action.equalsIgnoreCase("copy")) { if (fileDestData.equals("")) { c.setExceptionState(true, "File copy operation failed for file '" + filenameData + "': No destination file specified."); return new StringBuffer(); } FileChannel srcChannel; FileChannel destChannel; String filename = null; filename = currentDocroot + filenameData.toString(); if (vartype != null && vartype.equalsIgnoreCase("file")) { if (useFilename.indexOf("/") != -1) { useFilename = useFilename.substring(useFilename.lastIndexOf("/") + 1); } filename = c.getVariableContainer().getFileVariable(useFilename); } try { Debug.debug("Copying from file '" + filename + "' to '" + fileDestData.toString() + "'"); srcChannel = new FileInputStream(filename).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' failed to read: " + e.getMessage()); return new StringBuffer(); } try { destChannel = new FileOutputStream(currentDocroot + fileDestData.toString()).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy to '" + fileDestData + "' failed to write: " + e.getMessage()); return new StringBuffer(); } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", filenameData + " copy to " + fileDestData + ": File copy succeeded."); } else { return new StringBuffer("true"); } } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' to '" + fileDestData + "' failed: " + e.getMessage()); } } else if (action.equalsIgnoreCase("exists")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.exists()) { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "true"); } else { return new StringBuffer("true"); } } else { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "false"); } else { return new StringBuffer("false"); } } } else if (action.equalsIgnoreCase("mkdir")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.mkdirs()) { if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", "created"); } else { return new StringBuffer("true"); } } else { c.setExceptionState(true, "Unable to create directory '" + filenameData + "'"); } } else if (action.equalsIgnoreCase("info")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isAbsolute()) { fileType = "absolute"; } else if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (varname != null && !varname.equals("")) { c.getVariableContainer().setVariable(varname + ".length", fileLength); c.getVariableContainer().setVariable(varname + ".type", fileType); c.getVariableContainer().setVariable(varname + ".mode", fileMode); c.getVariableContainer().setVariable(varname + ".modtime", fileTime); } else { buffer = new StringBuffer(); buffer.append("<file name=\""); buffer.append(filenameData); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); return buffer; } } if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); }
|
00
|
Code Sample 1:
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
Code Sample 2:
void sortclasses() { int i, j; boolean domore; vclassptr = new int[numc]; for (i = 0; i < numc; i++) vclassptr[i] = i; domore = true; while (domore == true) { domore = false; for (i = 0; i < numc - 1; i++) { if (vclassctr[vclassptr[i]] < vclassctr[vclassptr[i + 1]]) { int temp = vclassptr[i]; vclassptr[i] = vclassptr[i + 1]; vclassptr[i + 1] = temp; domore = true; } } } }
|
11
|
Code Sample 1:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } }
|
00
|
Code Sample 1:
public void run() { try { if (netLoadAccount.loginsuccessful) { host = netLoadAccount.username + " | Netload.in"; } else { host = "Netload.in"; } status = UploadStatus.INITIALISING; initialize(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); if (netLoadAccount.loginsuccessful) { httppost.setHeader("Cookie", usercookie); } MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (netLoadAccount.loginsuccessful) { mpEntity.addPart("upload_hash", new StringBody(upload_hash)); } mpEntity.addPart("file", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); NULogger.getLogger().info("Now uploading your file into netload"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); status = UploadStatus.GETTINGLINK; HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); httpclient.getConnectionManager().shutdown(); if (response.containsHeader("Location")) { Header firstHeader = response.getFirstHeader("Location"); NULogger.getLogger().info(firstHeader.getValue()); uploadresponse = getData(firstHeader.getValue()); downloadlink = CommonUploaderTasks.parseResponse(uploadresponse, "The download link is: <br/>", "\" target=\"_blank\">"); downloadlink = downloadlink.substring(downloadlink.indexOf("href=\"")); downloadlink = downloadlink.replace("href=\"", ""); NULogger.getLogger().log(Level.INFO, "download link : {0}", downloadlink); deletelink = CommonUploaderTasks.parseResponse(uploadresponse, "The deletion link is: <br/>", "\" target=\"_blank\">"); deletelink = deletelink.substring(deletelink.indexOf("href=\"")); deletelink = deletelink.replace("href=\"", ""); NULogger.getLogger().log(Level.INFO, "delete link : {0}", deletelink); downURL = downloadlink; delURL = deletelink; uploadFinished(); } else { throw new Exception("There might be a problem with your internet connection or server error. Please try after some time :("); } } catch (Exception e) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e); uploadFailed(); } }
Code Sample 2:
public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
|
11
|
Code Sample 1:
public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; }
Code Sample 2:
public static void main(String[] args) { LogFrame.getInstance(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.trim().startsWith(DEBUG_PARAMETER_NAME + "=")) { properties.put(DEBUG_PARAMETER_NAME, arg.trim().substring(DEBUG_PARAMETER_NAME.length() + 1).trim()); if (properties.getProperty(DEBUG_PARAMETER_NAME).toLowerCase().equals(DEBUG_TRUE)) { DEBUG = true; } } else if (arg.trim().startsWith(AUTOCONNECT_PARAMETER_NAME + "=")) { properties.put(AUTOCONNECT_PARAMETER_NAME, arg.trim().substring(AUTOCONNECT_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SITE_CONFIG_URL_PARAMETER_NAME + "=")) { properties.put(SITE_CONFIG_URL_PARAMETER_NAME, arg.trim().substring(SITE_CONFIG_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_URL_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOC_ID_PARAMETER_NAME + "=")) { properties.put(DOC_ID_PARAMETER_NAME, arg.trim().substring(DOC_ID_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME.length() + 1).trim()); RichUIUtils.setDocServiceProxyFactoryClassname(properties.getProperty(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME)); } else { System.out.println("WARNING! Unknown or undefined parameter: '" + arg.trim() + "'"); } } System.out.println("Annotation Diff GUI startup parameters:"); System.out.println("------------------------------"); for (Object propName : properties.keySet()) { System.out.println(propName.toString() + "=" + properties.getProperty((String) propName)); } System.out.println("------------------------------"); if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) == null || properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() == 0) { String err = "Mandatory parameter '" + SITE_CONFIG_URL_PARAMETER_NAME + "' is missing.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } try { String context = System.getProperty(CONTEXT); if (context == null || "".equals(context)) { context = DEFAULT_CONTEXT; } String s = System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { File f = File.createTempFile("foo", ""); String gateHome = f.getParent().toString() + context; f.delete(); System.setProperty(GateConstants.GATE_HOME_PROPERTY_NAME, gateHome); f = new File(System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/plugins"); File f = new File(System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/gate.xml"); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) != null && properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() > 0) { File f = new File(System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME)); if (f.exists()) { f.delete(); } f.getParentFile().mkdirs(); f.createNewFile(); URL url = new URL(properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME)); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream(f); int i = is.read(); while (i != -1) { fos.write(i); i = is.read(); } fos.close(); is.close(); } try { Gate.init(); gate.Main.applyUserPreferences(); } catch (Exception e) { e.printStackTrace(); } } catch (Throwable e) { e.printStackTrace(); } MainFrame.getInstance().setVisible(true); MainFrame.getInstance().pack(); if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(DOC_ID_PARAMETER_NAME) == null || properties.getProperty(DOC_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + DOC_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowAnnDiffConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToAnnDiffGUI.getInstance().actionPerformed(null); } } else { ActionShowAnnDiffConnectDialog.getInstance().actionPerformed(null); } }
|
00
|
Code Sample 1:
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
Code Sample 2:
private void readFromFile1() throws DException { URL url1 = null; if (url == null) { url = getClass().getResource("/com/daffodilwoods/daffodildb/utils/parser/parser.schema"); try { url = new URL(url.getProtocol() + ":" + url.getPath().substring(0, url.getPath().indexOf("/parser.schema"))); } catch (MalformedURLException ex2) { ex2.printStackTrace(); throw new DException("DSE0", new Object[] { ex2 }); } try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } if (url1 == null) { throw new DException("DSE0", new Object[] { "Parser.schema file is missing in classpath." }); } } else { try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } } ArrayList arr1 = null; StringBuffer rule = null; try { LineNumberReader raf = new LineNumberReader(new BufferedReader(new InputStreamReader(url1.openStream()))); arr1 = new ArrayList(); rule = new StringBuffer(""); while (true) { String str1 = raf.readLine(); if (str1 == null) { break; } String str = str1.trim(); if (str.length() == 0) { if (rule.length() > 0) { arr1.add(rule.toString()); } rule = new StringBuffer(""); } else { rule.append(" ").append(str); } } raf.close(); } catch (IOException ex1) { ex1.printStackTrace(); throw new DException("DSE0", new Object[] { ex1 }); } if (rule.length() > 0) arr1.add(rule.toString()); for (int i = 0; i < arr1.size(); i++) { String str = (String) arr1.get(i); int index = str.indexOf("::="); if (index == -1) { P.pln("Error " + str); throw new DException("DSE0", new Object[] { "Rule is missing from parser.schema" }); } String key = str.substring(0, index).trim(); String value = str.substring(index + 3).trim(); Object o = fileEntries.put(key, value); if (o != null) { new Exception("Duplicate Defination for Rule [" + key + "] Value [" + value + "] Is Replaced By [" + o + "]").printStackTrace(); } } }
|
00
|
Code Sample 1:
private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); }
Code Sample 2:
public int extractDocumentsInternal(DocumentHolder holder, DocumentFactory docFactory) { FTPClient client = new FTPClient(); try { client.connect(site, port == 0 ? 21 : port); client.login(user, password); visitDirectory(client, "", path, holder, docFactory); client.disconnect(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { } return fileCount; }
|
00
|
Code Sample 1:
protected void innerProcess(ProcessorURI curi) throws InterruptedException { Pattern regexpr = curi.get(this, STRIP_REG_EXPR); ReplayCharSequence cs = null; try { cs = curi.getRecorder().getReplayCharSequence(); } catch (Exception e) { curi.getNonFatalFailures().add(e); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr != null) { s = cs.toString(); } else { Matcher m = regexpr.matcher(cs); s = m.replaceAll(" "); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
Code Sample 2:
private synchronized void awaitResponse() throws BOSHException { HttpEntity entity = null; try { HttpResponse httpResp = client.execute(post, context); entity = httpResp.getEntity(); byte[] data = EntityUtils.toByteArray(entity); String encoding = entity.getContentEncoding() != null ? entity.getContentEncoding().getValue() : null; if (ZLIBCodec.getID().equalsIgnoreCase(encoding)) { data = ZLIBCodec.decode(data); } else if (GZIPCodec.getID().equalsIgnoreCase(encoding)) { data = GZIPCodec.decode(data); } body = StaticBody.fromString(new String(data, CHARSET)); statusCode = httpResp.getStatusLine().getStatusCode(); sent = true; } catch (IOException iox) { abort(); toThrow = new BOSHException("Could not obtain response", iox); throw (toThrow); } catch (RuntimeException ex) { abort(); throw (ex); } }
|
00
|
Code Sample 1:
public List<AnalyzerResult> analyze(LWComponent c, boolean tryFallback) { List<AnalyzerResult> results = new ArrayList<AnalyzerResult>(); try { URL url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + c.getLabel()); if (flow != null) { url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + getSpecFromComponent(c)); } System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); XMLDecoder decoder = new XMLDecoder(url.openStream()); Map map = (Map) decoder.readObject(); for (Object key : map.keySet()) { results.add(new AnalyzerResult(key.toString(), map.get(key).toString())); } } catch (Exception ex) { ex.printStackTrace(); VueUtil.alert("Can't Execute Flow on the node " + c.getLabel(), "Can't Execute Seasr flow"); } return results; }
Code Sample 2:
private void processHelpFile() { InputStream in = null; if (line.hasOption("helpfile")) { OutputStream out = null; try { String filename = line.getOptionValue("helpfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); baseProperties.setProperty("helpfile", filename); IOUtils.copy(in, out); } 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); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return; } Properties props = new Properties(baseProperties); ClassLoader cl = this.getClass().getClassLoader(); Document doc = null; try { in = cl.getResourceAsStream(RESOURCE_PKG + "/help-doc.xml"); doc = XmlUtils.parse(in); } catch (XmlException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } transformResource(doc, "help-doc.xsl", props, "help-doc.html"); baseProperties.setProperty("helpfile", "help-doc.html"); }
|
00
|
Code Sample 1:
private void generate(String salt) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("No MD5", e); } long time = System.currentTimeMillis(); long rand = random.nextLong(); sbValueBeforeMD5.append(systemId); sbValueBeforeMD5.append(salt); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(Long.toString(rand)); md5.update(sbValueBeforeMD5.toString().getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); int position = 0; for (int j = 0; j < array.length; ++j) { if (position == 4 || position == 6 || position == 8 || position == 10) { sb.append('-'); } position++; int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b).toUpperCase()); } guidString = sb.toString().toUpperCase(); }
Code Sample 2:
public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req, ActionResponse res) throws Exception { boolean editor = false; req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, false); User user = _getUser(req); List<Role> roles = RoleFactory.getAllRolesForUser(user.getUserId()); for (Role role : roles) { if (role.getName().equals("Report Administrator") || role.getName().equals("Report Editor") || role.getName().equals("CMS Administrator")) { req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, true); editor = true; break; } } requiresInput = false; badParameters = false; newReport = false; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); String cmd = req.getParameter(Constants.CMD); Logger.debug(this, "Inside EditReportAction cmd=" + cmd); ReportForm rfm = (ReportForm) form; ArrayList<String> ds = (DbConnectionFactory.getAllDataSources()); ArrayList<DataSource> dsResults = new ArrayList<DataSource>(); for (String dataSource : ds) { DataSource d = rfm.getNewDataSource(); if (dataSource.equals(com.dotmarketing.util.Constants.DATABASE_DEFAULT_DATASOURCE)) { d.setDsName("DotCMS Datasource"); } else { d.setDsName(dataSource); } dsResults.add(d); } rfm.setDataSources(dsResults); httpReq.setAttribute("dataSources", rfm.getDataSources()); Long reportId = UtilMethods.parseLong(req.getParameter("reportId"), 0); String referrer = req.getParameter("referrer"); if (reportId > 0) { report = ReportFactory.getReport(reportId); ArrayList<String> adminRoles = new ArrayList<String>(); adminRoles.add(com.dotmarketing.util.Constants.ROLE_REPORT_ADMINISTRATOR); if (user.getUserId().equals(report.getOwner())) { _checkWritePermissions(report, user, httpReq, adminRoles); } if (cmd == null || !cmd.equals(Constants.EDIT)) { rfm.setSelectedDataSource(report.getDs()); rfm.setReportName(report.getReportName()); rfm.setReportDescription(report.getReportDescription()); rfm.setReportId(report.getInode()); rfm.setWebFormReport(report.isWebFormReport()); httpReq.setAttribute("selectedDS", report.getDs()); } } else { if (!editor) { throw new DotRuntimeException("user not allowed to create a new report"); } report = new Report(); report.setOwner(_getUser(req).getUserId()); newReport = true; } req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, report); if ((cmd != null) && cmd.equals(Constants.EDIT)) { if (Validator.validate(req, form, mapping)) { report.setReportName(rfm.getReportName()); report.setReportDescription(rfm.getReportDescription()); report.setWebFormReport(rfm.isWebFormReport()); if (rfm.isWebFormReport()) report.setDs("None"); else report.setDs(rfm.getSelectedDataSource()); String jrxmlPath = ""; String jasperPath = ""; try { HibernateUtil.startTransaction(); ReportFactory.saveReport(report); _applyPermissions(req, report); if (!rfm.isWebFormReport()) { if (UtilMethods.isSet(Config.getStringProperty("ASSET_REAL_PATH"))) { jrxmlPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"; jasperPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"; } else { jrxmlPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"); jasperPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"); } UploadPortletRequest upr = PortalUtil.getUploadPortletRequest(req); File importFile = upr.getFile("jrxmlFile"); if (importFile.exists()) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(importFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); File f = new File(jrxmlPath); FileChannel channelTo = new FileOutputStream(f).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); try { JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath); } catch (Exception e) { Logger.error(this, "Unable to compile or save jrxml: " + e.toString()); try { f = new File(jrxmlPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jrxml. This is usually a permissions problem."); } try { f = new File(jasperPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jasper. This is usually a permissions problem."); } HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", UtilMethods.htmlLineBreak(e.getMessage())); setForward(req, "portlet.ext.report.edit_report"); return; } JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath); ReportParameterFactory.deleteReportsParameters(report); _loadReportParameters(jasperReport.getParameters()); report.setRequiresInput(requiresInput); HibernateUtil.save(report); } else if (newReport) { HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", "message.report.compile.error"); setForward(req, "portlet.ext.report.edit_report"); return; } } HibernateUtil.commitTransaction(); HashMap params = new HashMap(); SessionMessages.add(req, "message", "message.report.upload.success"); params.put("struts_action", new String[] { "/ext/report/view_reports" }); referrer = com.dotmarketing.util.PortletURLUtil.getRenderURL(((ActionRequestImpl) req).getHttpServletRequest(), javax.portlet.WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, referrer); return; } catch (Exception ex) { HibernateUtil.rollbackTransaction(); Logger.error(this, "Unable to save Report: " + ex.toString()); File f; Logger.info(this, "Trying to delete jrxml"); try { f = new File(jrxmlPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jrxml. This is usually because the file doesn't exist."); } try { f = new File(jasperPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jasper. This is usually because the file doesn't exist."); } if (badParameters) { SessionMessages.add(req, "error", ex.getMessage()); } else { SessionMessages.add(req, "error", "message.report.compile.error"); } setForward(req, "portlet.ext.report.edit_report"); return; } } else { setForward(req, "portlet.ext.report.edit_report"); } } if ((cmd != null) && cmd.equals("downloadReportSource")) { ActionResponseImpl resImpl = (ActionResponseImpl) res; HttpServletResponse response = resImpl.getHttpServletResponse(); if (!downloadSourceReport(reportId, httpReq, response)) { SessionMessages.add(req, "error", "message.report.source.file.not.found"); } } setForward(req, "portlet.ext.report.edit_report"); }
|
11
|
Code Sample 1:
public static byte[] hashFile(File file) { long size = file.length(); long jump = (long) (size / (float) CHUNK_SIZE); MessageDigest digest; FileInputStream stream; try { stream = new FileInputStream(file); digest = MessageDigest.getInstance("SHA-256"); if (size < CHUNK_SIZE * 4) { readAndUpdate(size, stream, digest); } else { if (stream.skip(jump) != jump) return null; readAndUpdate(CHUNK_SIZE, stream, digest); if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null; readAndUpdate(CHUNK_SIZE, stream, digest); if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null; readAndUpdate(CHUNK_SIZE, stream, digest); digest.update(Long.toString(size).getBytes()); } return digest.digest(); } catch (FileNotFoundException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } catch (IOException e) { return null; } }
Code Sample 2:
public static String md5(String senha) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Ocorreu NoSuchAlgorithmException"); } md.update(senha.getBytes()); byte[] xx = md.digest(); String n2 = null; StringBuffer resposta = new StringBuffer(); for (int i = 0; i < xx.length; i++) { n2 = Integer.toHexString(0XFF & ((int) (xx[i]))); if (n2.length() < 2) { n2 = "0" + n2; } resposta.append(n2); } return resposta.toString(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.