label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); try { URL url = new URL("http://placekitten.com/g/500/250"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500); Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); output.eraseColor(Color.BLACK); Canvas canvas = new Canvas(output); canvas.drawBitmap(kitten, 125, 125, new Paint()); canvas.drawBitmap(frame, 0, 0, new Paint()); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); textPaint.setTextAlign(Align.CENTER); textPaint.setAntiAlias(true); textPaint.setTextSize(36); canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint); textPaint.setTextSize(24); canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint); ImageView imageView = (ImageView) this.findViewById(R.id.imageView); imageView.setImageBitmap(output); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private void doUpload(UploadKind uploadKind, WriteKind writeKind) throws Exception { int n = 512 * 1024; AtomicInteger total = new AtomicInteger(0); ServerSocket ss = startSinkServer(total); URL url = new URL("http://localhost:" + ss.getLocalPort() + "/test1"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); if (uploadKind == UploadKind.CHUNKED) { conn.setChunkedStreamingMode(-1); } else { conn.setFixedLengthStreamingMode(n); } OutputStream out = conn.getOutputStream(); if (writeKind == WriteKind.BYTE_BY_BYTE) { for (int i = 0; i < n; ++i) { out.write('x'); } } else { byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64 * 1024]; Arrays.fill(buf, (byte) 'x'); for (int i = 0; i < n; i += buf.length) { out.write(buf, 0, Math.min(buf.length, n - i)); } } out.close(); assertTrue(conn.getResponseCode() > 0); assertEquals(uploadKind == UploadKind.CHUNKED ? -1 : n, total.get()); }
|
00
|
Code Sample 1:
public String getHTTPContent(String sUrl, String encode, String cookie, String host, String referer) { HttpURLConnection connection = null; InputStream in = null; StringBuffer strResult = new StringBuffer(); try { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); if (!isStringNull(host)) this.setHttpInfo(connection, cookie, host, referer); connection.connect(); int httpStatus = connection.getResponseCode(); if (httpStatus != 200) log.info("getHTTPConent error httpStatus - " + httpStatus); in = new BufferedInputStream(connection.getInputStream()); String inputLine = null; byte[] b = new byte[40960]; int len = 0; while ((len = in.read(b)) > 0) { inputLine = new String(b, 0, len, encode); strResult.append(inputLine.replaceAll("[\t\n\r ]", " ")); } in.close(); } catch (IOException e) { log.warn("SpiderUtil getHTTPConent IOException -> ", e); } finally { if (in != null) try { in.close(); } catch (IOException e) { } } return strResult.toString(); }
Code Sample 2:
public static byte[] sendSmsRequest(String url, String param) { byte[] bytes = null; try { URL httpurl = new URL(url); HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection(); httpConn.setRequestProperty("Accept-Language", "zh-CN"); httpConn.setDoOutput(true); httpConn.setDoInput(true); PrintWriter out = new PrintWriter(httpConn.getOutputStream()); out.print(param); out.flush(); out.close(); InputStream ism = httpConn.getInputStream(); bytes = new byte[httpConn.getContentLength()]; ism.read(bytes); ism.close(); MsgPrint.showByteArray("result", bytes); } catch (Exception e) { return new byte[] { 0, 0, 0, 0 }; } return bytes; }
|
00
|
Code Sample 1:
private synchronized void configure() { final Map res = new HashMap(); try { final Enumeration resources = getConfigResources(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); while (resources.hasMoreElements()) { final URL url = (URL) resources.nextElement(); DefaultHandler saxHandler = new DefaultHandler() { private Group group; private StringBuffer tagContent = new StringBuffer(); public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("group".equals(qName)) { group = new Group(attributes.getValue("name")); String minimizeJs = attributes.getValue("minimize"); String minimizeCss = attributes.getValue("minimizeCss"); group.setMinimize(!"false".equals(minimizeJs)); group.setMinimizeCss("true".equals(minimizeCss)); } else if ("js".equals(qName) || "css".equals(qName) || "group-ref".equals(qName)) tagContent.setLength(0); } public void characters(char ch[], int start, int length) throws SAXException { tagContent.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { if ("group".equals(qName)) res.put(group.getName(), group); else if ("js".equals(qName)) group.getJsNames().add(tagContent.toString()); else if ("css".equals(qName)) group.getCssNames().add(tagContent.toString()); else if ("group-ref".equals(qName)) { String name = tagContent.toString(); Group subGroup = (Group) res.get(name); if (subGroup == null) throw new RuntimeException("Error parsing " + url.toString() + " <group-ref>" + name + "</group-ref> unknown"); group.getSubgroups().add(subGroup); } } }; try { saxParser.parse(url.openStream(), saxHandler); } catch (Throwable e) { log.warn(e.toString(), e); log.warn("Exception " + e.toString() + " ignored, let's move on.."); } } configurationFilesMaxModificationTime = findMaxConfigModificationTime(); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } this.groups = res; }
Code Sample 2:
public RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
|
00
|
Code Sample 1:
public static List<String> getFiles(int year, int month, int day, String type) throws Exception { ArrayList<String> list = new ArrayList<String>(); URL url = new URL(baseUrl + "/" + year + "/" + ((month > 9) ? month : ("0" + month)) + "/" + ((day > 9) ? day : ("0" + day))); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null && line != "") { if (line.startsWith("<tr>") && line.indexOf("[TXT]") >= 0) { int i = line.indexOf("href="); i = i + 6; int j = line.indexOf("\"", i); String filename = line.substring(i, j); if (filename.matches(".*" + type + ".*")) { list.add(filename); } } } br.close(); return list; }
Code Sample 2:
private void parse() throws ComponentRegistryException { try { HttpURLConnection connection = (HttpURLConnection) this.url.openConnection(); connection.setInstanceFollowRedirects(false); connection.connect(); int count = 0; while (String.valueOf(connection.getResponseCode()).startsWith("3")) { String location = connection.getHeaderField("Location"); logger.finest("Redirecting to " + location); connection.disconnect(); this.url = new URL(location); connection = (HttpURLConnection) this.url.openConnection(); connection.setInstanceFollowRedirects(false); connection.connect(); count++; if (count > 10) { throw new ComponentRegistryException("Too many redirect"); } } InputStream inputStream = connection.getInputStream(); InputStreamReader reader = new InputStreamReader(inputStream); HtmlRegistryParserCallback callback = new HtmlRegistryParserCallback(); ParserDelegator parser = new ParserDelegator(); parser.parse(reader, callback, false); } catch (IOException e) { throw new ComponentRegistryException(e); } }
|
11
|
Code Sample 1:
@Override public void run() { try { FileChannel out = new FileOutputStream(outputfile).getChannel(); long pos = 0; status.setText("Slučovač: Proces Slučování spuštěn.. Prosím čekejte.."); for (int i = 1; i <= noofparts; i++) { FileChannel in = new FileInputStream(originalfilename.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Slučovač: Slučuji část " + i + ".."); this.splitsize = in.size(); out.transferFrom(in, pos, splitsize); pos += splitsize; in.close(); if (deleteOnFinish) new File(originalfilename + ".v" + i).delete(); pb.setValue(100 * i / noofparts); } out.close(); status.setText("Slučovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Sloučeno!", "Slučovač", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileChannel input = new FileInputStream(srcFile).getChannel(); try { FileChannel output = new FileOutputStream(destFile).getChannel(); try { output.transferFrom(input, 0, input.size()); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
Code Sample 2:
public static String getURLContent(String urlPath, String charset) { BufferedReader reader = null; HttpURLConnection conn = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(urlPath); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setUseCaches(false); conn.setDefaultUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(60000); conn.connect(); int repCode = conn.getResponseCode(); if (repCode == 200) { int count = 0; char[] chBuffer = new char[1024]; BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); while ((count = input.read(chBuffer)) != -1) { buffer.append(chBuffer, 0, count); } } } catch (Exception ex) { logger.error("", ex); } finally { try { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception ex) { } } return buffer.toString(); }
|
00
|
Code Sample 1:
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(""); }
Code Sample 2:
public static File insertFileInto(File zipFile, File toInsert, String targetPath) { Zip64File zip64File = null; try { boolean compress = false; zip64File = new Zip64File(zipFile); FileEntry testEntry = getFileEntry(zip64File, targetPath); if (testEntry != null && testEntry.getMethod() == FileEntry.iMETHOD_DEFLATED) { compress = true; } processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath, toInsert), compress); if (testEntry != null) { log.info("[insertFileInto] Entry exists: " + testEntry.getName()); log.info("[insertFileInto] Will delete this entry before inserting: " + toInsert.getName()); if (!testEntry.isDirectory()) { zip64File.delete(testEntry.getName()); } else { log.info("[insertFileInto] Entry is a directory. " + "Will delete all files contained in this entry and insert " + toInsert.getName() + "and all nested files."); if (!targetPath.contains("/")) { targetPath = targetPath + "/"; } deleteFileEntry(zip64File, testEntry); log.info("[insertFileInto] Entry successfully deleted."); } log.info("[insertFileInto] Writing new Entry: " + targetPath); EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } else { EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } log.info("[insertFileInto] Done! Added " + toInsert.getName() + " to zip."); zip64File.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new File(zip64File.getDiskFile().getFileName()); }
|
00
|
Code Sample 1:
public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
Code Sample 2:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
|
11
|
Code Sample 1:
public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); }
Code Sample 2:
@Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
|
00
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
11
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public static boolean copyFile(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) return false; if (sourceFileName.equals(destFileName)) return false; try { java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); try { byte[] buf = new byte[31000]; int read = in.read(buf); while (read > -1) { out.write(buf, 0, read); read = in.read(buf); } } finally { in.close(); out.close(); } } catch (Exception e) { System.out.println(e.toString()); return false; } return true; }
|
00
|
Code Sample 1:
public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; boolean ok = true; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
Code Sample 2:
public ArrayList parseFile(File newfile) throws IOException { String s; String firstName; String header; String name = null; Integer PVLoggerID = new Integer(0); String[] tokens; int nvalues = 0; double num1, num2, num3; double xoffset = 1.0; double xdelta = 1.0; double yoffset = 1.0; double ydelta = 1.0; double zoffset = 1.0; double zdelta = 1.0; boolean readfit = false; boolean readraw = false; boolean zerodata = false; boolean baddata = false; boolean harpdata = false; ArrayList fitparams = new ArrayList(); ArrayList xraw = new ArrayList(); ArrayList yraw = new ArrayList(); ArrayList zraw = new ArrayList(); ArrayList sraw = new ArrayList(); ArrayList sxraw = new ArrayList(); ArrayList syraw = new ArrayList(); ArrayList szraw = new ArrayList(); URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; firstName = (String) tokens[0]; if (((String) tokens[0]).length() == 0) { readraw = false; readfit = false; continue; } if ((nvalues == 4) && (!firstName.startsWith("---"))) { if ((Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.)) { zerodata = true; } else { zerodata = false; } if (tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")) { baddata = true; } else { baddata = false; } } if (firstName.startsWith("start")) { header = s; } if (firstName.indexOf("WS") > 0) { if (name != null) { dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); } name = tokens[0]; readraw = false; readfit = false; zerodata = false; baddata = false; harpdata = false; fitparams.clear(); xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); } if (firstName.startsWith("Area")) ; if (firstName.startsWith("Ampl")) ; if (firstName.startsWith("Mean")) ; if (firstName.startsWith("Sigma")) { fitparams.add(new Double(Double.parseDouble(tokens[3]))); fitparams.add(new Double(Double.parseDouble(tokens[1]))); fitparams.add(new Double(Double.parseDouble(tokens[5]))); } if (firstName.startsWith("Offset")) ; if (firstName.startsWith("Slope")) ; if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Raw"))) { readraw = true; continue; } if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Fit"))) { readfit = true; continue; } if ((firstName.contains("Harp"))) { xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); harpdata = true; readraw = true; name = tokens[0]; continue; } if (firstName.startsWith("---")) continue; if (harpdata == true) { if (((String) tokens[0]).length() != 0) { if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } else { sxraw.add(new Double(Double.parseDouble(tokens[0]))); xraw.add(new Double(Double.parseDouble(tokens[1]))); syraw.add(new Double(Double.parseDouble(tokens[2]))); yraw.add(new Double(Double.parseDouble(tokens[3]))); szraw.add(new Double(Double.parseDouble(tokens[4]))); zraw.add(new Double(Double.parseDouble(tokens[5]))); } } continue; } if (readraw && (!zerodata) && (!baddata)) { sraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); sxraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); syraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); szraw.add(new Double(Double.parseDouble(tokens[0]))); yraw.add(new Double(Double.parseDouble(tokens[1]))); zraw.add(new Double(Double.parseDouble(tokens[2]))); xraw.add(new Double(Double.parseDouble(tokens[3]))); } if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } } dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); wiredata.add((Integer) PVLoggerID); return wiredata; }
|
00
|
Code Sample 1:
@Override public TDSScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); TDSScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); }
Code Sample 2:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); }
|
00
|
Code Sample 1:
private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); }
Code Sample 2:
public static void copy(final File source, final File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); dest.setLastModified(source.lastModified()); } finally { close(in); close(out); } }
|
00
|
Code Sample 1:
public static byte[] wrapBMP(Image image) throws IOException { if (image.getOriginalType() != Image.ORIGINAL_BMP) throw new IOException("Only BMP can be wrapped in WMF."); InputStream imgIn; byte data[] = null; if (image.getOriginalData() == null) { imgIn = image.url().openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int b = 0; while ((b = imgIn.read()) != -1) out.write(b); imgIn.close(); data = out.toByteArray(); } else data = image.getOriginalData(); int sizeBmpWords = (data.length - 14 + 1) >>> 1; ByteArrayOutputStream os = new ByteArrayOutputStream(); writeWord(os, 1); writeWord(os, 9); writeWord(os, 0x0300); writeDWord(os, 9 + 4 + 5 + 5 + (13 + sizeBmpWords) + 3); writeWord(os, 1); writeDWord(os, 14 + sizeBmpWords); writeWord(os, 0); writeDWord(os, 4); writeWord(os, META_SETMAPMODE); writeWord(os, 8); writeDWord(os, 5); writeWord(os, META_SETWINDOWORG); writeWord(os, 0); writeWord(os, 0); writeDWord(os, 5); writeWord(os, META_SETWINDOWEXT); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeDWord(os, 13 + sizeBmpWords); writeWord(os, META_DIBSTRETCHBLT); writeDWord(os, 0x00cc0020); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); os.write(data, 14, data.length - 14); if ((data.length & 1) == 1) os.write(0); writeDWord(os, 3); writeWord(os, 0); os.close(); return os.toByteArray(); }
Code Sample 2:
public static String getEncryptedPassword(String clearTextPassword) { if (StringUtil.isEmpty(clearTextPassword)) return ""; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(clearTextPassword.getBytes()); return new sun.misc.BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { _log.error("Failed to encrypt password.", e); } return ""; }
|
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:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
|
00
|
Code Sample 1:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException(className + "Cannot overwrite existing file: " + dest.getAbsolutePath()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
Code Sample 2:
public void doNew(Vector userId, String shareFlag, String folderId) throws AddrException { DBOperation dbo = null; Connection connection = null; PreparedStatement ps = null; ResultSet rset = null; String sql = "insert into " + SHARE_TABLE + " values(?,?,?)"; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); for (int i = 0; i < userId.size(); i++) { String user = (String) userId.elementAt(i); ps = connection.prepareStatement(sql); ps.setInt(1, Integer.parseInt(folderId)); ps.setInt(2, Integer.parseInt(user)); ps.setString(3, shareFlag); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new Exception("error"); } } connection.commit(); } catch (Exception ex) { if (connection != null) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } logger.error("���������ļ�����Ϣʧ��, " + ex.getMessage()); throw new AddrException("���������ļ�����Ϣʧ��,һ�������ļ���ֻ�ܹ����ͬһ�û�һ��!"); } finally { close(rset, null, ps, connection, dbo); } }
|
00
|
Code Sample 1:
public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } this.currentGafFilePath = this.url; try { if (this.httpURL != null) { LOG.info("Reading URL :" + httpURL); InputStream is = this.httpURL.openStream(); int index = this.httpURL.toString().lastIndexOf('/'); String file = this.httpURL.toString().substring(index + 1); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), "tmp-" + file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); is = new FileInputStream(downloadLocation); if (url.endsWith(".gz")) { is = new GZIPInputStream(is); } this.currentGafFile = this.currentGafFilePath.substring(this.currentGafFilePath.lastIndexOf("/") + 1); this.httpURL = null; return is; } else { String file = files[counter++].getName(); this.currentGafFile = file; if (!this.currentGafFilePath.endsWith(file)) currentGafFilePath += file; LOG.info("Returning input stream for the file: " + file); _connect(); ftpClient.changeWorkingDirectory(path); InputStream is = ftpClient.retrieveFileStream(file); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); System.out.println("Download complete....."); is = new FileInputStream(downloadLocation); if (file.endsWith(".gz")) { is = new GZIPInputStream(is); } return is; } } catch (IOException ex) { throw new RuntimeException(ex); } }
Code Sample 2:
public void addUser(String name, String unit, String organizeName, int userId, int orgId, String email) { Connection connection = null; PreparedStatement ps = null; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { connection = dbo.getConnection(); ps = connection.prepareStatement(INSERT_USER); ps.setInt(1, AddrslistMainDao.getNewID()); ps.setInt(2, -100); ps.setString(3, name.substring(0, 1)); ps.setString(4, name.substring(1)); ps.setString(5, unit); ps.setString(6, organizeName); ps.setString(7, ""); ps.setString(8, email); ps.setString(9, ""); ps.setString(10, ""); ps.setString(11, ""); ps.setString(12, ""); ps.setString(13, ""); ps.setString(14, ""); ps.setString(15, ""); ps.setString(16, ""); ps.setString(17, ""); ps.setString(18, ""); ps.setInt(19, userId); ps.setInt(20, orgId); ps.executeUpdate(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { ps.close(); connection.close(); dbo.close(); } catch (Exception e) { } } }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent ev) { if (fileChooser == null) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)"); fileFilter.addExtension("jar"); fileFilter.addExtension("zip"); fileChooser.setFileFilter(fileFilter); } if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) { String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); JarFile jar = null; try { jar = new JarFile(fileChooser.getSelectedFile()); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } urls[0] = fileChooser.getSelectedFile().toURL(); } catch (IOException e) { Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e); return; } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { String entryName = (String) it.next(); try { devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class)); } catch (IOException e) { Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e); return; } } for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) en.nextElement(); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), fileChooser.getSelectedFile().getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(fileChooser.getSelectedFile(), deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } lsDevicesModel.addElement(entry); Config.addDeviceEntry(entry); } lsDevices.setSelectedValue(entry, true); } catch (IOException e) { Message.error("Error adding device profile, " + Message.getCauseMessage(e), e); return; } } }
Code Sample 2:
@Override public boolean saveCart(Carrito cart, boolean completado, String date, String formPago) { Connection conexion = null; PreparedStatement insertHistorial = null; PreparedStatement insertCarrito = null; boolean exito = false; try { conexion = pool.getConnection(); conexion.setAutoCommit(false); insertHistorial = conexion.prepareStatement("INSERT INTO " + nameBD + ".HistorialCarritos VALUES (?,?,?,?,?,?)"); insertHistorial.setString(1, cart.getUser()); insertHistorial.setString(2, cart.getCodigo()); insertHistorial.setString(3, date); insertHistorial.setDouble(4, cart.getPrecio()); insertHistorial.setString(5, formPago); insertHistorial.setBoolean(6, completado); int filasAfectadas = insertHistorial.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); } else { insertCarrito = conexion.prepareStatement("INSERT INTO " + nameBD + ".Carritos VALUES (?,?,?,?,?)"); Iterator<String> iteradorProductos = cart.getArticulos().keySet().iterator(); while (iteradorProductos.hasNext()) { String key = iteradorProductos.next(); Producto prod = getProduct(key); int cantidad = cart.getArticulos().get(key); insertCarrito.setString(1, cart.getCodigo()); insertCarrito.setString(2, prod.getCodigo()); insertCarrito.setString(3, prod.getNombre()); insertCarrito.setDouble(4, prod.getPrecio()); insertCarrito.setInt(5, cantidad); filasAfectadas = insertCarrito.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); break; } insertCarrito.clearParameters(); } conexion.commit(); exito = true; } } catch (SQLException ex) { logger.log(Level.SEVERE, "Error añadiendo carrito al registro", ex); try { conexion.rollback(); } catch (SQLException ex1) { logger.log(Level.SEVERE, "Error haciendo rollback de la transacción para insertar carrito en el registro", ex1); } } finally { cerrarConexionYStatement(conexion, insertCarrito, insertHistorial); } return exito; }
|
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:
private void copyfile(File srcFile, File dstDir) throws FileNotFoundException, IOException { if (srcFile.isDirectory()) { File newDestDir = new File(dstDir, srcFile.getName()); newDestDir.mkdir(); String fileNameList[] = srcFile.list(); for (int i = 0; i < fileNameList.length; i++) { File newSouceFile = new File(srcFile, fileNameList[i]); copyfile(newSouceFile, newDestDir); } } else { File newDestFile = new File(dstDir, srcFile.getName()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(newDestFile); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); long i; Logger.log("copyFile before- copiedSize = " + copiedSize); for (i = 0; i < srcFile.length() - BLOCK_LENGTH; i += BLOCK_LENGTH) { synchronized (this) { inChannel.transferTo(i, BLOCK_LENGTH, outChannel); copiedSize += BLOCK_LENGTH; } } synchronized (this) { inChannel.transferTo(i, srcFile.length() - i, outChannel); copiedSize += srcFile.length() - i; } Logger.log("copyFile after copy- copiedSize = " + copiedSize + "srcFile.length = " + srcFile.length() + "diff = " + (copiedSize - srcFile.length())); in.close(); out.close(); outChannel = null; Logger.log("File copied."); } }
|
00
|
Code Sample 1:
private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
Code Sample 2:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
|
00
|
Code Sample 1:
public Gif(URL url) throws BadElementException, IOException { super(url); type = GIF; InputStream is = null; try { is = url.openStream(); if (is.read() != 'G' || is.read() != 'I' || is.read() != 'F') { throw new BadElementException(url.toString() + " is not a valid GIF-file."); } skip(is, 3); scaledWidth = is.read() + (is.read() << 8); setRight((int) scaledWidth); scaledHeight = is.read() + (is.read() << 8); setTop((int) scaledHeight); } finally { if (is != null) { is.close(); } plainWidth = width(); plainHeight = height(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); }
|
11
|
Code Sample 1:
private byte[] hash(String data, HashAlg alg) { try { MessageDigest digest = MessageDigest.getInstance(alg.toString()); digest.update(data.getBytes()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { } return null; }
Code Sample 2:
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); }
|
11
|
Code Sample 1:
public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
|
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 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) { } }
|
00
|
Code Sample 1:
private String getClassname(Bundle bundle) { URL urlEntry = bundle.getEntry("jdbcBundleInfo.xml"); InputStream in = null; try { in = urlEntry.openStream(); try { StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("<!DOCTYPE")) { sb.append(line); } } SAXBuilder builder = new SAXBuilder(false); Document doc = builder.build(new StringReader(sb.toString())); Element eRoot = doc.getRootElement(); if ("jdbcBundleInfo".equals(eRoot.getName())) { Attribute atri = eRoot.getAttribute("className"); if (atri != null) { return atri.getValue(); } } } catch (JDOMException e) { } } catch (IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } return null; }
Code Sample 2:
public void createNewFile(String filePath, InputStream in) throws IOException { FileOutputStream out = null; try { File file = newFileRef(filePath); FileHelper.createNewFile(file, true); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
|
00
|
Code Sample 1:
public static Properties load(URL url) { if (url == null) { return new Properties(); } InputStream in = null; try { in = url.openStream(); Properties ret = new Properties(); ret.load(in); return ret; } catch (IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error("Error closing", e); } } } }
Code Sample 2:
private void addPlugin(URL url) throws IOException { logger.debug("Adding plugin with URL {}", url); InputStream in = url.openStream(); try { Properties properties = new Properties(); properties.load(in); plugins.add(new WtfPlugin(properties)); } finally { in.close(); } }
|
00
|
Code Sample 1:
public String readFile(String filename) throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(USERNAME, PASSWORD); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); boolean success = ftpClient.retrieveFile(filename, outputStream); ftpClient.disconnect(); if (!success) { throw new IOException("Retrieve file failed: " + filename); } return outputStream.toString(); }
Code Sample 2:
public void guardarRecordatorio() { try { if (espaciosLlenos()) { guardarCantidad(); String dat = ""; String filenametxt = String.valueOf("recordatorio" + cantidadArchivos + ".txt"); String filenamezip = String.valueOf("recordatorio" + cantidadArchivos + ".zip"); cantidadArchivos++; dat += identificarDato(datoSeleccionado) + "\n"; dat += String.valueOf(mesTemporal) + "\n"; dat += String.valueOf(anoTemporal) + "\n"; dat += horaT.getText() + "\n"; dat += lugarT.getText() + "\n"; dat += actividadT.getText() + "\n"; File archivo = new File(filenametxt); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(dat); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filenamezip); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File(filenametxt); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry(filenametxt); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); JOptionPane.showMessageDialog(null, "El recordatorio ha sido guardado con exito", "Recordatorio Guardado", JOptionPane.INFORMATION_MESSAGE); marco.hide(); marco.dispose(); establecerMarca(); table.clearSelection(); } else JOptionPane.showMessageDialog(null, "Debe llenar los espacios de Hora, Lugar y Actividad", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
00
|
Code Sample 1:
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String forw = null; try { int maxUploadSize = 50000000; MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize); String descrizione = multi.getParameter("text"); File myFile = multi.getFile("uploadfile"); String filePath = multi.getOriginalFileName("uploadfile"); String path = "C:\\files\\"; try { FileInputStream inStream = new FileInputStream(myFile); FileOutputStream outStream = new FileOutputStream(path + myFile.getName()); while (inStream.available() > 0) { outStream.write(inStream.read()); } inStream.close(); outStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } forw = "../sendDoc.jsp"; request.setAttribute("contentType", context.getMimeType(path + myFile.getName())); request.setAttribute("text", descrizione); request.setAttribute("path", path + myFile.getName()); request.setAttribute("size", Long.toString(myFile.length()) + " Bytes"); RequestDispatcher rd = request.getRequestDispatcher(forw); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public String generateKey(String className, String methodName, String text, String meaning) { if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); }
|
00
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
private static boolean insereTutorial(final Connection con, final Tutorial tut, final Autor aut, final Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodTutorial(con, tut); String titulo = tut.getTitulo().replaceAll("['\"]", ""); String coment = tut.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO tutorial VALUES(" + tut.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO tut_aut VALUES(" + tut.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "TUTORIAL: Database error", JOptionPane.ERROR_MESSAGE); System.out.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
|
00
|
Code Sample 1:
public void init(File file) { InputStream is = null; ByteArrayOutputStream os = null; try { is = new FileInputStream(file); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); } catch (Throwable e) { throw new VisualizerEngineException("Unexcpected exception while reading MDF file", e); } if (simulationEngine != null) simulationEngine.stopSimulation(); simulationEngine = new TrafficAsynchSimulationEngine(); simulationEngine.init(MDFReader.read(os.toByteArray())); simulationEngineThread = null; }
Code Sample 2:
public boolean crear() { int result = 0; String sql = "insert into ronda" + "(divisionxTorneo_idDivisionxTorneo, fechaRonda, nRonda, estado ) " + "values (?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(unaRonda); result = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (result > 0); }
|
00
|
Code Sample 1:
public static Image getPluginImage(final Object plugin, final String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
Code Sample 2:
public static List<String> unTar(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); TarArchiveInputStream in = new TarArchiveInputStream(inputStream); TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextTarEntry(); } in.close(); return result; }
|
11
|
Code Sample 1:
public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } }
Code Sample 2:
public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
|
11
|
Code Sample 1:
public static String toMD5(String seed) { MessageDigest md5 = null; StringBuffer temp_sb = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(seed.getBytes()); byte[] array = md5.digest(); temp_sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x10) temp_sb.append('0'); temp_sb.append(Integer.toHexString(b)); } } catch (NoSuchAlgorithmException err) { err.printStackTrace(); } return temp_sb.toString(); }
Code Sample 2:
private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; }
|
11
|
Code Sample 1:
private String callPage(String urlStr) throws IOException { URL url = new URL(urlStr); BufferedReader reader = null; StringBuilder result = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } } finally { if (reader != null) reader.close(); } return result.toString(); }
Code Sample 2:
public static String getContent(String path, String encoding) throws IOException { URL url = new URL(path); URLConnection conn = url.openConnection(); conn.setDoOutput(true); InputStream inputStream = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, encoding); StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); sb.append("\n"); } return sb.toString(); }
|
11
|
Code Sample 1:
public static void fileCopy(String src, String dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); int read = -1; byte[] buf = new byte[8192]; while ((read = fis.read(buf)) != -1) { fos.write(buf, 0, read); } fos.flush(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
|
11
|
Code Sample 1:
public static String getHash(String key) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); return new BigInteger(digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return key; } }
Code Sample 2:
public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { System.out.println(e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); }
|
00
|
Code Sample 1:
public URLConnection getResourceConnection(String name) throws ResourceException { if (context == null) throw new ResourceException("There is no ServletContext to get the requested resource"); URL url = null; try { url = context.getResource("/WEB-INF/scriptags/" + name); return url.openConnection(); } catch (Exception e) { throw new ResourceException(String.format("Resource '%s' could not be found (url: %s)", name, url), e); } }
Code Sample 2:
protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
|
00
|
Code Sample 1:
private void downloadFile(String directory, String fileName) { URL url = null; String urlstr = updateURL + directory + fileName; int position = 0; try { Logger.msg(threadName + "Download new file from " + urlstr); url = new URL(urlstr); URLConnection conn = url.openConnection(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(updateDirectory + System.getProperty("file.separator") + fileName)); int i = in.read(); while (i != -1) { if (isInterrupted()) { setWasInterrupted(); in.close(); out.flush(); out.close(); interrupt(); return; } out.write(i); i = in.read(); position += 1; if (position % 1000 == 0) { Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } } } Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } in.close(); out.flush(); out.close(); Logger.msg(threadName + "Saved file " + fileName + " to " + updateDirectory + System.getProperty("file.separator") + fileName); } catch (Exception e) { Logger.err(threadName + "Error (" + e.toString() + ")"); } }
Code Sample 2:
public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
|
00
|
Code Sample 1:
public void handler(List<GoldenBoot> gbs, TargetPage target) { try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; String include = "Top Scorers"; while ((line = reader.readLine()) != null) { if (line.indexOf(include) != -1) { buildGildenBoot(line, gbs); break; } } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
Code Sample 2:
private Vector _sort(Pair[] ps, String id, int num) { Vector ret = new Vector(); boolean swapped = true; int j = 0; Pair tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < ps.length - j; i++) { if (ps[i].c > ps[i + 1].c) { tmp = ps[i]; ps[i] = ps[i + 1]; ps[i + 1] = tmp; swapped = true; } } } int m = Math.min(num, ps.length); for (int i = m - 1; i >= 0; i--) { if (id == null) ret.addElement(ps[i].n); else if (ps[i].n.startsWith(id) && !ps[i].n.equals(id)) ret.addElement(ps[i].n); } return ret; }
|
00
|
Code Sample 1:
public MapInfo getMap(double latitude, double longitude, double wanted_mapblast_scale, int image_width, int image_height, String file_path_wo_extension, ProgressListener progress_listener) throws IOException { try { if (web_request_ == null) { web_request_ = new HttpRequester(HOST_NAME); } int zoom_index = getZoomLevelIndex(wanted_mapblast_scale); int google_zoom_level = GOOGLE_ZOOM_LEVELS[zoom_index]; double mapblast_scale = POSSIBLE_GOOGLE_SCALES[zoom_index]; Tile tile = new Tile(latitude, longitude, google_zoom_level); SimplePoint coords = tile.getTileLatLong(); SimplePoint google_xy = tile.getTileCoord(); MapInfo map_info = new MapInfo(); map_info.setLatitude(coords.getX()); map_info.setLongitude(coords.getY()); map_info.setScale((float) mapblast_scale); map_info.setWidth(256); map_info.setHeight(256); map_info.setFilename(file_path_wo_extension + "png"); Object[] params = new Object[] { new Integer(google_xy.getX()), new Integer(google_xy.getY()), new Integer(google_zoom_level) }; MessageFormat message_format = new MessageFormat(GOOGLE_MAPS_URL, Locale.US); String url_string = message_format.format(params); URL url = new URL(url_string); if (Debug.DEBUG) Debug.println("map_download", "loading map from url: " + url); URLConnection connection = url.openConnection(); if (resources_.getBoolean(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USE)) { String proxy_userid = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USERNAME); String proxy_password = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_PASSWORD); String auth_string = proxy_userid + ":" + proxy_password; auth_string = "Basic " + new sun.misc.BASE64Encoder().encode(auth_string.getBytes()); connection.setRequestProperty("Proxy-Authorization", auth_string); } connection.connect(); String mime_type = connection.getContentType().toLowerCase(); if (!mime_type.startsWith("image")) { if (mime_type.startsWith("text")) { HTMLViewerFrame viewer = new HTMLViewerFrame(url); viewer.setSize(640, 480); viewer.setTitle("ERROR on loading url: " + url); viewer.setVisible(true); throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type + "\nPage is displayed in HTML frame."); } throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type); } int content_length = connection.getContentLength(); if (content_length < 0) progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, Integer.MIN_VALUE); else progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, content_length); String extension = mime_type.substring(mime_type.indexOf('/') + 1); String filename = file_path_wo_extension + extension; FileOutputStream out = new FileOutputStream(filename); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE); int sum_bytes = 0; int num_bytes = 0; while ((num_bytes = in.read(buffer)) != -1) { out.write(buffer, 0, num_bytes); sum_bytes += num_bytes; progress_listener.actionProgress(PROGRESS_LISTENER_ID, sum_bytes); } progress_listener.actionEnd(PROGRESS_LISTENER_ID); in.close(); out.close(); return (map_info); } catch (NoRouteToHostException nrhe) { nrhe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = nrhe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_NO_ROUTE_TO_HOST_MESSAGE); throw new IOException(message); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = fnfe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_FILE_NOT_FOUND_MESSAGE); throw new IOException(message); } catch (Exception e) { progress_listener.actionEnd(PROGRESS_LISTENER_ID); e.printStackTrace(); String message = e.getMessage(); if (message == null) { Throwable cause = e.getCause(); if (cause != null) message = cause.getMessage(); } throw new IOException(message); } }
Code Sample 2:
public static List<String> retrieveLanguages() throws Exception { List<String> result = new ArrayList<String>(); URL url = new URL("http://translatewiki.net/w/i.php?title=Special:MessageGroupStats&group=out-osm-site"); String str = StreamUtil.toString(url.openStream()); Pattern pattern = Pattern.compile(".*language=([^;\"]+).*"); Matcher m = pattern.matcher(str); while (m.find()) { String lang = m.group(1); if (!result.contains(lang)) { result.add(lang); } } return result; }
|
11
|
Code Sample 1:
public static File copyFile(File from, File to) throws IOException { FileOutputStream fos = new FileOutputStream(to); FileInputStream fis = new FileInputStream(from); FileChannel foc = fos.getChannel(); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return to; }
Code Sample 2:
public void notifyIterationEnds(final IterationEndsEvent event) { log.info("moving files..."); File source = new File("deqsim.log"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log to its iteration directory."); } } int parallelCnt = 0; source = new File("deqsim.log." + parallelCnt); while (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log." + parallelCnt)); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log." + parallelCnt + " to its iteration directory."); } parallelCnt++; source = new File("deqsim.log." + parallelCnt); } source = new File("loads_out.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("loads_out.txt")); try { IOUtils.copyFile(source, destination); } catch (FileNotFoundException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } catch (IOException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } destination = new File("loads_in.txt"); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move loads_out.txt to loads_in.txt."); } } source = new File("linkprocs.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("linkprocs.txt")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move linkprocs.txt to its iteration directory."); } } }
|
11
|
Code Sample 1:
public static void checkAndUpdateGameData() { new ErrThread() { @Override public void handledRun() throws Throwable { try { URL url = new URL(ONLINE_CLIENT_DATA + "gamedata.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); int lastversion = 0; String readHeader1 = br.readLine(); String readHeader2 = br.readLine(); String[] parts = readHeader2.split(" "); lastversion = new Integer(parts[1]); GameDatabase.loadVersion(); if (GameDatabase.version < lastversion) { Logger.log(LogTypes.LOG, "Downloading new gamedata"); BufferedOutputStream bo = null; File destfile = new File(GameDatabase.dataFilePath); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); bo.write((readHeader1 + "\n").getBytes()); bo.write((readHeader2 + "\n").getBytes()); int readedbyte; while ((readedbyte = br.read()) != -1) { bo.write(readedbyte); } bo.flush(); try { br.close(); bo.close(); } catch (Exception ex) { Logger.log(ex); } } } catch (java.net.UnknownHostException unknownHost) { Logger.log("Sourceforge is down, cannot update gamedata"); } catch (Exception e) { JOptionPane.showMessageDialog(FrameOrganizer.getClientFrame(), "The gamedata is outdated, but Coopnet couldn't update it!", "Gamedata outdated", JOptionPane.INFORMATION_MESSAGE); throw e; } finally { GameDatabase.loadVersion(); GameDatabase.load("", GameDatabase.dataFilePath); GameDatabase.detectGames(); } } }.start(); }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
11
|
Code Sample 1:
public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public static String getMD5(String _pwd) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(_pwd.getBytes()); return toHexadecimal(new String(md.digest()).getBytes()); } catch (NoSuchAlgorithmException x) { x.printStackTrace(); return ""; } }
|
00
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public InputStream doRemoteCall(NamedList<String> params) throws IOException { String protocol = "http"; String host = getHost(); int port = Integer.parseInt(getPort()); StringBuilder sb = new StringBuilder(); for (Map.Entry entry : params) { Object key = entry.getKey(); Object value = entry.getValue(); sb.append(key).append("=").append(value).append("&"); } sb.setLength(sb.length() - 1); String file = "/" + getUrl() + "/?" + sb.toString(); URL url = new URL(protocol, host, port, file); logger.debug(url.toString()); InputStream stream; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { stream = conn.getInputStream(); } catch (IOException ioe) { InputStream is = conn.getErrorStream(); if (is != null) { String msg = getStringFromInputStream(conn.getErrorStream()); throw new IOException(msg); } else { throw ioe; } } return stream; }
|
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 FileBean create(MimeTypeBean mimeType, SanBean san) throws SQLException { long fileId = 0; DataSource ds = getDataSource(DEFAULT_DATASOURCE); Connection conn = ds.getConnection(); try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.execute(NEXT_FILE_ID); ResultSet rs = stmt.getResultSet(); while (rs.next()) { fileId = rs.getLong(NEXTVAL); } PreparedStatement pstmt = conn.prepareStatement(INSERT_FILE); pstmt.setLong(1, fileId); pstmt.setLong(2, mimeType.getId()); pstmt.setLong(3, san.getId()); pstmt.setLong(4, WORKFLOW_ATTENTE_VALIDATION); int nbrow = pstmt.executeUpdate(); if (nbrow == 0) { throw new SQLException(); } conn.commit(); closeRessources(conn, pstmt); } catch (SQLException e) { log.error("Can't FileDAOImpl.create " + e.getMessage()); conn.rollback(); throw e; } FileBean fileBean = new FileBean(); return fileBean; }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { closeQuietly(in); closeQuietly(out); } return success; }
Code Sample 2:
protected static void copyFile(File from, File to) throws IOException { if (!from.isFile() || !to.isFile()) { throw new IOException("Both parameters must be files. from is " + from.isFile() + ", to is " + to.isFile()); } FileChannel in = (new FileInputStream(from)).getChannel(); FileChannel out = (new FileOutputStream(to)).getChannel(); in.transferTo(0, from.length(), out); in.close(); out.close(); }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile, boolean overwrite) throws IOException, DirNotFoundException, FileNotFoundException, FileExistsAlreadyException { File destDir = new File(destFile.getParent()); if (!destDir.exists()) { throw new DirNotFoundException(destDir.getAbsolutePath()); } if (!sourceFile.exists()) { throw new FileNotFoundException(sourceFile.getAbsolutePath()); } if (!overwrite && destFile.exists()) { throw new FileExistsAlreadyException(destFile.getAbsolutePath()); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); }
Code Sample 2:
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); WebResponse response = wc.getResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void addImageDB(String pictogramsPath, String pictogramToAddPath, String language, String type, String word) { try { Class.forName("org.sqlite.JDBC"); String fileName = pictogramsPath + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { int idL = 0, idT = 0; G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select id from language where name=\"" + language + "\""); while (rs.next()) { idL = rs.getInt("id"); } rs.close(); stat.close(); stat = G.conn.createStatement(); rs = stat.executeQuery("select id from type where name=\"" + type + "\""); while (rs.next()) { idT = rs.getInt("id"); } rs.close(); stat.close(); String id = pictogramToAddPath.substring(pictogramToAddPath.lastIndexOf(File.separator) + 1, pictogramToAddPath.length()); String idOrig = id; String pathSrc = pictogramToAddPath; String pathDst = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, word.toLowerCase()); stmt.setInt(2, idL); stmt.setInt(3, idT); stmt.setString(4, id); stmt.setString(5, idOrig); stmt.executeUpdate(); stmt.close(); G.conn.close(); } } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public String doUpload(@ParamName(name = "file") MultipartFile file, @ParamName(name = "uploadDirectory") String _uploadDirectory) throws IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); String tempUploadDir = MewitProperties.getTemporaryUploadDirectory(); if (!tempUploadDir.endsWith("/") && !tempUploadDir.endsWith("\\")) { tempUploadDir += "\\"; } String fileName = null; int position = file.getOriginalFilename().lastIndexOf("."); if (position <= 0) { fileName = java.util.UUID.randomUUID().toString(); } else { fileName = java.util.UUID.randomUUID().toString() + file.getOriginalFilename().substring(position); } File outputFile = new File(tempUploadDir, fileName); log(INFO, "writing the content of uploaded file to: " + outputFile); FileOutputStream fos = new FileOutputStream(outputFile); IOUtils.copy(file.getInputStream(), fos); file.getInputStream().close(); fos.close(); return doUploadFile(sessionId, outputFile, file.getOriginalFilename()); }
Code Sample 2:
@Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
|
00
|
Code Sample 1:
public void logout(String cookieString) throws NetworkException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_LOGOUT); if (cookieString != null && cookieString.length() != 0) get.setHeader("Cookie", cookieString); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
public LineIterator iterator() { LineIterator ret; final String charsetname; final Charset charset; final CharsetDecoder charsetDecoder; synchronized (this) { charsetname = this.charsetname; charset = this.charset; charsetDecoder = this.charsetDecoder; } try { if (charsetDecoder != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charsetDecoder); else if (charset != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charset); else if (charsetname != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, Charset.forName(charsetname)); else ret = new LineIterator(this, url.openStream(), returnNullUponEof, (Charset) null); synchronized (openedIterators) { openedIterators.add(ret); } return ret; } catch (IOException e) { throw new IllegalStateException(e); } }
|
00
|
Code Sample 1:
private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
protected void doRequest(HttpServletRequest request, HttpServletResponse response, boolean inGet) throws ServletException, IOException { response.setHeader("Server", WebConsoleServlet.SERVER_STRING); try { String requestedFilename = request.getRequestURI().substring(1); URL url = new URL(getJarFileName() + "/"); JarURLConnection jarConnection = (JarURLConnection) (url.openConnection()); JarFile jarFile = jarConnection.getJarFile(); String negotiatedFilename = null; ZipEntry zipEntry = null; zipEntry = negotiateImageFile(jarFile, requestedFilename, isIE6OrEarlier(request.getHeader("User-Agent"))); if (zipEntry == null) { zipEntry = jarFile.getEntry(requestedFilename); } else { negotiatedFilename = zipEntry.getName(); } if (zipEntry == null || zipEntry.isDirectory()) { handleFileNotFound(inGet, request, response); return; } int fileSize = (int) zipEntry.getSize(); response.setContentLength(fileSize); if (negotiatedFilename != null) { response.setContentType(getContentType(negotiatedFilename)); } else { response.setContentType(getContentType(request.getRequestURI())); } InputStream in = jarFile.getInputStream(zipEntry); BufferedInputStream bufferedInputStream = new BufferedInputStream(in); byte[] file = new byte[fileSize]; int bytesRead = bufferedInputStream.read(file); bufferedInputStream.close(); if (bytesRead == fileSize && cachingEnabled) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); java.util.Date today = new java.util.Date(); String date = formatter.format(GenericUtils.addOrSubstractDaysFromDate(today, 365)); response.setHeader("Expires", date); } OutputStream outputStream = response.getOutputStream(); outputStream.write(file); } catch (FileNotFoundException e) { handleFileNotFound(inGet, request, response); } catch (IOException e) { } catch (Throwable t) { Application.getApplication().logExceptionEvent(EventLogMessage.EventType.WEB_ERROR, t); } }
|
11
|
Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
|
11
|
Code Sample 1:
@Override public Object execute(ExecutionEvent event) throws ExecutionException { URL url; try { url = new URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt"); InputStream inputStream = url.openConnection().getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
private static String getProviderName(URL url, PrintStream err) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String result = null; while (true) { String line = reader.readLine(); if (line == null) { break; } int commentPos = line.indexOf('#'); if (commentPos >= 0) { line = line.substring(0, commentPos); } line = line.trim(); int len = line.length(); if (len != 0) { if (result != null) { print(err, "checkconfig.multiproviders", url.toString()); return null; } result = line; } } if (result == null) { print(err, "checkconfig.missingprovider", url.toString()); return null; } return result; } catch (IOException e) { print(err, "configconfig.read", url.toString(), e); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
|
11
|
Code Sample 1:
@SuppressWarnings("unchecked") private List<String> getLogFile() { String homeServer = ""; Realm realm = null; if (null == node) { if (null != System.getProperty("ThinClientManager.server.Codebase")) try { homeServer = new URL(System.getProperty("ThinClientManager.server.Codebase")).getHost(); } catch (final MalformedURLException e1) { e1.printStackTrace(); } } else { realm = (Realm) node.getLookup().lookup(Realm.class); if (null != realm.getSchemaProviderName()) homeServer = realm.getSchemaProviderName(); else if (null != realm.getConnectionDescriptor().getHostname()) homeServer = realm.getConnectionDescriptor().getHostname(); } if (homeServer.length() == 0) homeServer = "localhost"; try { final URL url = new URL("http", homeServer, 8080, fileName); final BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); final ArrayList<String> lines = new ArrayList<String>(); String line; if (isClient) { while ((line = br.readLine()) != null) if (line.contains(macAdress)) lines.add(line); if (lines.size() == 0) lines.add(Messages.getString("LogDetailView.getLogFile.NoEntrysForTC", macAdress)); } else while ((line = br.readLine()) != null) lines.add(line); br.close(); if (lines.size() == 0) lines.add(Messages.getString("LogDetailView.getLogFile.NoEntrys")); return lines; } catch (final MalformedURLException e) { e.printStackTrace(); ErrorManager.getDefault().notify(e); } catch (final IOException e) { e.printStackTrace(); ErrorManager.getDefault().notify(e); } return Collections.EMPTY_LIST; }
Code Sample 2:
private static Vector<String> getIgnoreList() { try { URL url = DeclarationTranslation.class.getClassLoader().getResource("ignorelist"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); Vector<String> ret = new Vector<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { ret.add(line); } return ret; } catch (Exception e) { return null; } }
|
00
|
Code Sample 1:
private static synchronized void find(String name) throws SAXException, IOException { if (c_cache.containsKey(name)) return; CustomHandler handler = null; URL url = null; String validatorFiles = (String) Config.getProperty(Config.PROP_RULES_ENGINE_VALIDATORS_URL_LIST, XML_FILE); for (StringTokenizer strtknzr = new StringTokenizer(validatorFiles, ","); strtknzr.hasMoreTokens(); ) { String validatorFile = strtknzr.nextToken(); try { url = URLHelper.newExtendedURL(validatorFile); } catch (MalformedURLException e) { url = null; } if (url == null) throw new FileNotFoundException("File not found - " + validatorFile); try { handler = new CustomHandler(name); XMLReader reader = XMLReaderFactory.createXMLReader(PARSER_NAME); reader.setContentHandler(handler); reader.setEntityResolver(new DefaultEntityResolver()); reader.setErrorHandler(new DefaultErrorHandler()); reader.parse(new InputSource(url.openStream())); } catch (SAXException e) { if (SUCCESS_MESSAGE.equals(e.getMessage()) && handler != null) break; else throw e; } catch (IOException e) { throw e; } if (handler.getFieldValidatorMetaData() != null) break; } c_cache.put(name, handler != null ? handler.getFieldValidatorMetaData() : null); }
Code Sample 2:
protected void initializeFromURL(URL url) throws IOException { URLConnection connection = url.openConnection(); String message = this.validateURLConnection(connection, DBASE_CONTENT_TYPES); if (message != null) { throw new IOException(message); } this.channel = Channels.newChannel(WWIO.getBufferedInputStream(connection.getInputStream())); this.initialize(); }
|
11
|
Code Sample 1:
public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuilder hexString = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
Code Sample 2:
public static String encryptPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest digester = MessageDigest.getInstance("sha-256"); digester.reset(); digester.update("Carmen Sandiago".getBytes()); return asHex(digester.digest(password.getBytes("UTF-8"))); }
|
00
|
Code Sample 1:
public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); 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("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } }
Code Sample 2:
public void removeBodyPart(int iPart) throws MessagingException, ArrayIndexOutOfBoundsException { if (DebugFile.trace) { DebugFile.writeln("Begin DBMimeMultipart.removeBodyPart(" + String.valueOf(iPart) + ")"); DebugFile.incIdent(); } DBMimeMessage oMsg = (DBMimeMessage) getParent(); DBFolder oFldr = ((DBFolder) oMsg.getFolder()); Statement oStmt = null; ResultSet oRSet = null; String sDisposition = null, sFileName = null; boolean bFound; try { oStmt = oFldr.getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (DebugFile.trace) DebugFile.writeln("Statement.executeQuery(SELECT " + DB.id_disposition + "," + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart) + ")"); oRSet = oStmt.executeQuery("SELECT " + DB.id_disposition + "," + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart)); bFound = oRSet.next(); if (bFound) { sDisposition = oRSet.getString(1); if (oRSet.wasNull()) sDisposition = "inline"; sFileName = oRSet.getString(2); } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; if (!bFound) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("Part not found"); } if (!sDisposition.equals("reference") && !sDisposition.equals("pointer")) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("Only parts with reference or pointer disposition can be removed from a message"); } else { if (sDisposition.equals("reference")) { try { File oRef = new File(sFileName); if (oRef.exists()) oRef.delete(); } catch (SecurityException se) { if (DebugFile.trace) DebugFile.writeln("SecurityException " + sFileName + " " + se.getMessage()); if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("SecurityException " + sFileName + " " + se.getMessage(), se); } } oStmt = oFldr.getConnection().createStatement(); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate(DELETE FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart) + ")"); oStmt.executeUpdate("DELETE FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart)); oStmt.close(); oStmt = null; oFldr.getConnection().commit(); } } catch (SQLException sqle) { if (oRSet != null) { try { oRSet.close(); } catch (Exception ignore) { } } if (oStmt != null) { try { oStmt.close(); } catch (Exception ignore) { } } try { oFldr.getConnection().rollback(); } catch (Exception ignore) { } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBMimeMultipart.removeBodyPart()"); } }
|
11
|
Code Sample 1:
private InputStream urlToInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", IE); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); String encoding = conn.getContentEncoding(); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) return new GZIPInputStream(conn.getInputStream()); else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else return conn.getInputStream(); }
Code Sample 2:
private ChangeCapsule fetchServer(OWLOntology ontologyURI, Long sequenceNumber) throws IOException { String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer"; requestString += "?fetch=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8"); requestString += "&number" + sequenceNumber; URL url = new URL(requestString); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer returned = new StringBuffer(); String str; while (null != ((str = input.readLine()))) { returned.append(str); } input.close(); ChangeCapsule cp = new ChangeCapsule(returned.toString()); return cp; }
|
00
|
Code Sample 1:
private URLConnection openConnection(final URL url) throws IOException { try { return (URLConnection) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return url.openConnection(); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
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 md5(String string) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString((result[i] & 0xFF) | 0x100).toLowerCase().substring(1, 3)); } return hexString.toString(); }
Code Sample 2:
public byte[] md5(String clearText) { MessageDigest md; byte[] digest; try { md = MessageDigest.getInstance("MD5"); md.update(clearText.getBytes()); digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.toString()); } return digest; }
|
11
|
Code Sample 1:
protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } }
Code Sample 2:
public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
|
00
|
Code Sample 1:
public static String getSSHADigest(String password, String salt) { String digest = null; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(password.getBytes()); sha.update(salt.getBytes()); byte[] pwhash = sha.digest(); digest = "{SSHA}" + new String(Base64.encode(concatenate(pwhash, salt.getBytes()))); } catch (NoSuchAlgorithmException nsae) { CofaxToolsUtil.log("Algorithme SHA-1 non supporte a la creation du hashage" + nsae + id); } return digest; }
Code Sample 2:
public static void test() { try { Pattern pattern = Pattern.compile("[0-9]{3}\\. <a href='(.*)\\.html'>(.*)</a><br />"); URL url = new URL("http://farmfive.com/"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; int count = 0; while ((line = br.readLine()) != null) { Matcher match = pattern.matcher(line); if (match.matches()) { System.out.println(match.group(1) + " " + match.group(2)); count++; } } System.out.println(count + " counted"); br.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copy(File inputFile, File target) throws IOException { if (!inputFile.exists()) return; OutputStream output = new FileOutputStream(target); InputStream input = new BufferedInputStream(new FileInputStream(inputFile)); int b; while ((b = input.read()) != -1) output.write(b); output.close(); input.close(); }
Code Sample 2:
public static boolean copy(String source, String dest) { int bytes; byte array[] = new byte[BUFFER_LEN]; try { InputStream is = new FileInputStream(source); OutputStream os = new FileOutputStream(dest); while ((bytes = is.read(array, 0, BUFFER_LEN)) > 0) os.write(array, 0, bytes); is.close(); os.close(); return true; } catch (IOException e) { return false; } }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public MsgRecvInfo[] recvMsg(MsgRecvReq msgRecvReq) throws SQLException { String updateSQL = " update dyhikemomessages set receive_id = ?, receive_Time = ? where mo_to =? and receive_id =0 limit 20"; String selectSQL = " select MOMSG_ID,mo_from,mo_to,create_time,mo_content from dyhikemomessages where receive_id =? "; String insertSQL = " insert into t_receive_history select * from dyhikemomessages where receive_id =? "; String deleteSQL = " delete from dyhikemomessages where receive_id =? "; Logger logger = Logger.getLogger(this.getClass()); ArrayList msgInfoList = new ArrayList(); String mo_to = msgRecvReq.getAuthInfo().getUserName(); MsgRecvInfo[] msgInfoArray = new ototype.MsgRecvInfo[0]; String receiveTime = Const.DF.format(new Date()); logger.debug("recvMsgNew1"); Connection conn = null; try { int receiveID = this.getSegquence("receiveID"); conn = this.getJdbcTemplate().getDataSource().getConnection(); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement(updateSQL); pstmt.setInt(1, receiveID); pstmt.setString(2, receiveTime); pstmt.setString(3, mo_to); int recordCount = pstmt.executeUpdate(); logger.info(recordCount + " record(s) got"); if (recordCount > 0) { pstmt = conn.prepareStatement(selectSQL); pstmt.setInt(1, receiveID); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { MsgRecvInfo msg = new MsgRecvInfo(); msg.setDestMobile(rs.getString("mo_to")); msg.setRecvAddi(rs.getString("mo_to")); msg.setSendAddi(rs.getString("MO_FROM")); msg.setContent(rs.getString("mo_content")); msg.setRecvDate(rs.getString("create_time")); msgInfoList.add(msg); } msgInfoArray = (MsgRecvInfo[]) msgInfoList.toArray(new MsgRecvInfo[msgInfoList.size()]); pstmt = conn.prepareStatement(insertSQL); pstmt.setInt(1, receiveID); pstmt.execute(); pstmt = conn.prepareStatement(deleteSQL); pstmt.setInt(1, receiveID); pstmt.execute(); conn.commit(); } logger.debug("recvMsgNew2"); return msgInfoArray; } catch (SQLException e) { conn.rollback(); throw e; } finally { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest, boolean preserveFileDate) throws IOException { if (src.exists() && src.isDirectory()) { throw new IOException("source file exists but is a directory"); } if (dest.exists() && dest.isDirectory()) { dest = new File(dest, src.getName()); } if (!dest.exists()) { dest.createNewFile(); } FileChannel srcCH = null; FileChannel destCH = null; try { srcCH = new FileInputStream(src).getChannel(); destCH = new FileOutputStream(dest).getChannel(); destCH.transferFrom(srcCH, 0, srcCH.size()); } finally { closeQuietly(srcCH); closeQuietly(destCH); } if (src.length() != dest.length()) { throw new IOException("Failed to copy full contents from '" + src + "' to '" + dest + "'"); } if (preserveFileDate) { dest.setLastModified(src.lastModified()); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
private 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 int executeUpdateJT(String sql, Object[][] paramsList) { Connection connection = null; connection = this.getConnection(); try { connection.setAutoCommit(false); } catch (SQLException e1) { e1.printStackTrace(); } PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < paramsList.length; i++) { if (connection != null && !connection.isClosed()) { InputStream is = null; if (paramsList[i].length > 0) { for (int j = 0; j < paramsList[i].length; j++) { Object obj = paramsList[i][j]; if (obj.getClass().equals(Class.forName("java.io.File"))) { File file = (File) obj; is = new FileInputStream(file); preparedStatement.setBinaryStream(j + 1, is, (int) file.length()); } else if (obj.getClass().equals(Class.forName("java.util.Date"))) { java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); preparedStatement.setString(j + 1, sdf.format((Date) obj)); } else { preparedStatement.setObject(j + 1, obj); } } } preparedStatement.executeUpdate(); if (is != null) { is.close(); } ; } } } catch (Exception e) { System.out.println("发生错误,数据回滚!"); e.printStackTrace(); try { connection.rollback(); return 0; } catch (SQLException e1) { e1.printStackTrace(); } } try { connection.commit(); return 1; } catch (SQLException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { log.error("未能正确关闭数据库连接!", e); System.out.println("未能正确关闭数据库连接!"); e.printStackTrace(); } } return -1; }
|
00
|
Code Sample 1:
public static String getWebPage(URL urlObj) { try { String content = ""; InputStreamReader is = new InputStreamReader(urlObj.openStream()); BufferedReader reader = new BufferedReader(is); String line; while ((line = reader.readLine()) != null) { content += line; } return content; } catch (IOException e) { throw new Error("The page " + quote(urlObj.toString()) + "could not be retrieved." + "\nThis is could be caused by a number of things:" + "\n" + "\n - the computer hosting the web page you want is down, or has returned an error" + "\n - your computer does not have Internet access" + "\n - the heat death of the universe has occurred, taking down all web servers with it"); } }
Code Sample 2:
public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); }
|
11
|
Code Sample 1:
public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while downloading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { } }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
00
|
Code Sample 1:
private String clientLogin(AuthInfo authInfo) throws AuthoricationRequiredException { logger.fine("clientLogin."); try { String url = "https://www.google.com/accounts/ClientLogin"; HttpPost httpPost = new HttpPost(url); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE")); params.add(new BasicNameValuePair("Email", authInfo.getEmail())); params.add(new BasicNameValuePair("Passwd", new String(authInfo.getPassword()))); params.add(new BasicNameValuePair("service", "ah")); params.add(new BasicNameValuePair("source", "client.kotan-server.appspot.com")); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = clientManager.httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { entity.consumeContent(); throw new AuthoricationRequiredException(EntityUtils.toString(entity)); } BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); while (true) { String line = reader.readLine(); if (line == null) break; if (line.startsWith("Auth=")) { return line.substring("Auth=".length()); } } reader.close(); throw new AuthoricationRequiredException("Login failure."); } catch (IOException e) { throw new AuthoricationRequiredException(e); } }
Code Sample 2:
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); } }
|
11
|
Code Sample 1:
private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); }
Code Sample 2:
public String readFile(String filename) throws UnsupportedEncodingException, FileNotFoundException, IOException { File f = new File(baseDir); f = new File(f, filename); StringWriter w = new StringWriter(); Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); IOUtils.copy(fr, w); fr.close(); w.close(); String contents = w.toString(); return contents; }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test1.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.encrypt(reader, writer, key, mode); }
Code Sample 2:
protected Object getMethodKey(String methodName, Object[] args) { StringBuffer key = new StringBuffer(methodName.trim().replace(" ", ".")).append("."); for (Object o : args) { if (o != null) key.append(o.hashCode()); } LOGGER.info("Generation key ->" + key.toString()); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); messageDigest.reset(); messageDigest.update(key.toString().getBytes(Charset.forName("UTF8"))); final byte[] resultByte = messageDigest.digest(); String hex = null; for (int i = 0; i < resultByte.length; i++) { hex = Integer.toHexString(0xFF & resultByte[i]); if (hex.length() < 2) { key.append("0"); } key.append(hex); } } catch (NoSuchAlgorithmException e) { LOGGER.severe("No hash generated for method key! " + StackTraceUtil.getStackTrace(e)); } LOGGER.info("Generation key ->" + key.toString()); return new String(key); }
|
00
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static String base64HashedString(String v) { String base64HashedPassword = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(v.getBytes()); String hashedPassword = new String(md.digest()); sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); base64HashedPassword = enc.encode(hashedPassword.getBytes()); } catch (java.security.NoSuchAlgorithmException e) { throw new NSForwardException(e, "Couldn't find the SHA hash algorithm; perhaps you do not have the SunJCE security provider installed properly?"); } return base64HashedPassword; }
|
00
|
Code Sample 1:
private Element getXmlFromGeoNetwork(String urlIn, Session userSession) throws FailedActionException { Element results = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); String cookie = (String) userSession.getAttribute("usercookie.object"); if (cookie != null) conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); } finally { in.close(); } } catch (Exception e) { throw new FailedActionException(FailedActionReason.SYSTEM_ERROR); } return results; }
Code Sample 2:
private void copyFile(File from, File to) throws IOException { FileUtils.ensureParentDirectoryExists(to); byte[] buffer = new byte[1024]; int read; FileInputStream is = new FileInputStream(from); FileOutputStream os = new FileOutputStream(to); while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } is.close(); os.close(); }
|
00
|
Code Sample 1:
public static String downloadWebpage2(String address) throws MalformedURLException, IOException { URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); String encoding = conn.getContentEncoding(); InputStream is = null; if(encoding != null && encoding.equalsIgnoreCase("gzip")) { is = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { is = new InflaterInputStream(conn.getInputStream()); } else { is = conn.getInputStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
Code Sample 2:
private void writeResponse(final Collection<? extends Resource> resources, final HttpServletResponse response) throws IOException { for (final Resource resource : resources) { InputStream in = null; try { in = resource.getInputStream(); final OutputStream out = response.getOutputStream(); final long bytesCopied = IOUtils.copyLarge(in, out); if (bytesCopied < 0L) throw new StreamCorruptedException("Bad number of copied bytes (" + bytesCopied + ") for resource=" + resource.getFilename()); if (logger.isDebugEnabled()) logger.debug("writeResponse(" + resource.getFile() + ") copied " + bytesCopied + " bytes"); } finally { if (in != null) in.close(); } } }
|
11
|
Code Sample 1:
public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
protected void doDownload(S3Bucket bucket, S3Object s3object) throws Exception { String key = s3object.getKey(); key = trimPrefix(key); String[] path = key.split("/"); String fileName = path[path.length - 1]; String dirPath = ""; for (int i = 0; i < path.length - 1; i++) { dirPath += path[i] + "/"; } File outputDir = new File(downloadFileOutputDir + "/" + dirPath); if (outputDir.exists() == false) { outputDir.mkdirs(); } File outputFile = new File(outputDir, fileName); long size = s3object.getContentLength(); if (outputFile.exists() && outputFile.length() == size) { return; } long startTime = System.currentTimeMillis(); log.info("Download start.S3 file=" + s3object.getKey() + " local file=" + outputFile.getAbsolutePath()); FileOutputStream fout = null; S3Object dataObject = null; try { fout = new FileOutputStream(outputFile); dataObject = s3.getObject(bucket, s3object.getKey()); InputStream is = dataObject.getDataInputStream(); IOUtils.copyStream(is, fout); downloadedFileList.add(key); long downloadTime = System.currentTimeMillis() - startTime; log.info("Download complete.Estimete time=" + downloadTime + "ms " + IOUtils.toBPSText(downloadTime, size)); } catch (Exception e) { log.error("Download fail. s3 file=" + key, e); outputFile.delete(); throw e; } finally { IOUtils.closeNoException(fout); if (dataObject != null) { dataObject.closeDataInputStream(); } } }
|
00
|
Code Sample 1:
private String readScriptFromURL(URL context, String s) { Object content = null; URL url; try { url = new URL(context, s); } catch (MalformedURLException e) { return null; } try { content = url.getContent(); } catch (UnknownServiceException e) { Class jar_class; try { jar_class = Class.forName("java.net.JarURLConnection"); } catch (Exception e2) { return null; } Object jar; try { jar = url.openConnection(); } catch (IOException e2) { return null; } if (jar == null) { return null; } try { Method m = jar_class.getMethod("openConnection", ((java.lang.Class[]) null)); content = m.invoke(jar, ((java.lang.Object[]) null)); } catch (Exception e2) { return null; } } catch (IOException e) { return null; } catch (SecurityException e) { return null; } if (content instanceof String) { return (String) content; } else if (content instanceof InputStream) { InputStream fs = (InputStream) content; try { byte charArray[] = new byte[fs.available()]; fs.read(charArray); return new String(charArray); } catch (IOException e2) { return null; } finally { closeInputStream(fs); } } else { return null; } }
Code Sample 2:
public static void testString(String string, String expected) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(string.getBytes(), 0, string.length()); String result = toString(md.digest()); System.out.println(expected); System.out.println(result); if (!expected.equals(result)) System.out.println("NOT EQUAL!"); } catch (Exception x) { x.printStackTrace(); } }
|
00
|
Code Sample 1:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente = '" + 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 GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
private synchronized jdbcResultSet executeHTTP(String s) throws SQLException { byte result[]; try { URL url = new URL(sConnect); String p = StringConverter.unicodeToHexString(sUser); p += "+" + StringConverter.unicodeToHexString(sPassword); p += "+" + StringConverter.unicodeToHexString(s); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStream os = c.getOutputStream(); os.write(p.getBytes(ENCODING)); os.close(); c.connect(); InputStream is = (InputStream) c.getContent(); BufferedInputStream in = new BufferedInputStream(is); int len = c.getContentLength(); result = new byte[len]; for (int i = 0; i < len; i++) { int r = in.read(); result[i] = (byte) r; } } catch (Exception e) { throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.getMessage()); } return new jdbcResultSet(new Result(result)); }
|
11
|
Code Sample 1:
public void trimAndWriteNewSff(OutputStream out) throws IOException { TrimParser trimmer = new TrimParser(); SffParser.parseSFF(untrimmedSffFile, trimmer); tempOut.close(); headerBuilder.withNoIndex().numberOfReads(numberOfTrimmedReads); SffWriter.writeCommonHeader(headerBuilder.build(), out); InputStream in = null; try { in = new FileInputStream(tempReadDataFile); IOUtils.copyLarge(in, out); } finally { IOUtil.closeAndIgnoreErrors(in); } }
Code Sample 2:
private void copyFile(String sourceFilename, String targetFilename) throws IOException { File source = new File(sourceFilename); File target = new File(targetFilename); InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
11
|
Code Sample 1:
public final String hashPassword(final String password) { try { if (salt == null) { salt = new byte[16]; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(System.currentTimeMillis()); sr.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] hash = md.digest(); for (int i = 0; i < (1999); i++) { md.reset(); hash = md.digest(hash); } return byteToString(hash, 60); } catch (Exception exception) { log.error(exception); return null; } }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(sid); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } }
|
00
|
Code Sample 1:
public static String md5(String text, String charset) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } msgDigest.update(text.getBytes()); byte[] bytes = msgDigest.digest(); byte tb; char low; char high; char tmpChar; String md5Str = new String(); for (int i = 0; i < bytes.length; i++) { tb = bytes[i]; tmpChar = (char) ((tb >>> 4) & 0x000f); if (tmpChar >= 10) { high = (char) (('a' + tmpChar) - 10); } else { high = (char) ('0' + tmpChar); } md5Str += high; tmpChar = (char) (tb & 0x000f); if (tmpChar >= 10) { low = (char) (('a' + tmpChar) - 10); } else { low = (char) ('0' + tmpChar); } md5Str += low; } return md5Str; }
Code Sample 2:
private static List<String> getContent(URL url) throws IOException { final HttpURLConnection http = (HttpURLConnection) url.openConnection(); try { http.connect(); final int code = http.getResponseCode(); if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]"); return getContent(http); } finally { http.disconnect(); } }
|
11
|
Code Sample 1:
private String generateServiceId(ObjectName mbeanName) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(mbeanName.toString().getBytes()); StringBuffer hexString = new StringBuffer(); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString().toUpperCase(); } catch (Exception ex) { RuntimeException runTimeEx = new RuntimeException("Unexpected error during MD5 hash creation, check your JRE"); runTimeEx.initCause(ex); throw runTimeEx; } }
Code Sample 2:
public synchronized String encrypt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
11
|
Code Sample 1:
@Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } }
Code Sample 2:
static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); }
|
00
|
Code Sample 1:
public VeecheckResult performRequest(VeecheckVersion version, String uri) throws ClientProtocolException, IOException, IllegalStateException, SAXException { HttpClient client = new DefaultHttpClient(); HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT); HttpGet request = new HttpGet(version.substitute(uri)); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); try { StatusLine line = response.getStatusLine(); if (line.getStatusCode() != 200) throw new IOException("Request failed: " + line.getReasonPhrase()); Header header = response.getFirstHeader(HTTP.CONTENT_TYPE); Encoding encoding = identityEncoding(header); VeecheckResult handler = new VeecheckResult(version); Xml.parse(entity.getContent(), encoding, handler); return handler; } finally { entity.consumeContent(); } }
Code Sample 2:
private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
|
11
|
Code Sample 1:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ACCOUNT")); pst.setInt(1, acc.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
Code Sample 2:
public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
00
|
Code Sample 1:
protected Boolean lancerincident(long idbloc, String Etatbloc, java.util.GregorianCalendar datebloc, long idServeur, String niveau, String message) { String codeerr; Boolean retour = false; Boolean SauvegardeEtatAutocommit; int etat; acgtools_core.AcgIO.SortieLog(new Date() + " - Appel de la fonction Lancer incident"); Statement statement = null; ResultSet resultat = null; String RequeteSQL = ""; acgtools_core.AcgIO.SortieLog(new Date() + " - nouvel incident pour le bloc : " + acgtools_core.AcgIO.RetourneDate(datebloc)); try { this.con = db.OpenConnection(); SauvegardeEtatAutocommit = this.con.getAutoCommit(); this.con.setAutoCommit(false); if (idbloc == 0) { idbloc = this.CreationBloc(idServeur); if (idbloc == 0) { retour = false; acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la création du bloc"); this.con.rollback(); this.con.close(); return false; } } acgtools_core.AcgIO.SortieLog(new Date() + " - bloc : " + idbloc); etat = this.ChargerEtatServeur(idbloc, datebloc); if (etat != 2) { statement = con.createStatement(); acgtools_core.AcgIO.SortieLog(new Date() + " - Etat chargé"); RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job ='" + idbloc + "' " + "AND incref_err_numer NOT IN " + "(SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_err_etat='c') " + "AND incref_err_numer NOT IN " + "(SELECT incenc_err_numer FROM tbl_incident_encours " + "WHERE incenc_err_etat='c') ;"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (!resultat.next()) { resultat.close(); RequeteSQL = "INSERT INTO tbl_incident_ref " + "(incref_cde_job,incref_err_date,incref_err_etat,incref_niv_crimd,incref_err_msg,incref_err_srvnm)" + "VALUES ('" + idbloc + "','" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','" + Etatbloc + "','" + niveau + "','" + message + "','" + idServeur + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job = '" + idbloc + "' " + "AND incref_err_srvnm = '" + idServeur + "' " + "AND incref_err_date = '" + acgtools_core.AcgIO.RetourneDate(datebloc) + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (resultat.next()) { codeerr = resultat.getString("incref_err_numer"); resultat.close(); RequeteSQL = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + message + "','" + niveau + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); acgtools_core.AcgIO.SortieLog(new Date() + " - Incident inséré dans la base de données"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, acgtools_core.AcgIO.RetourneDate(datebloc), message); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'historique"); this.CreerHistorique(codeerr); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(true); retour = true; } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Problème d'insertion du nouvel incident dans la base"); retour = false; } } else { codeerr = resultat.getString("incref_err_numer"); acgtools_core.AcgIO.SortieLog(new Date() + " - Numéro de l'erreur trouvé. Numéro =" + codeerr); RequeteSQL = "SELECT incenc_err_etat FROM tbl_incident_encours " + "WHERE incenc_err_numer='" + codeerr + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (!resultat.next()) { resultat.close(); acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident."); String RequeteSQLInsert = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + "Incident non cloturé - " + message + "','" + niveau + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQLInsert); statement.execute(RequeteSQLInsert); resultat = statement.executeQuery(RequeteSQL); } else { resultat = statement.executeQuery(RequeteSQL); acgtools_core.AcgIO.SortieLog(new Date() + " - Incident correctement positionné dans encours"); } if (resultat.next()) { switch(Etatbloc.charAt(0)) { case 'c': { acgtools_core.AcgIO.SortieLog(new Date() + " - Cloture de l'incident."); RequeteSQL = "UPDATE tbl_incident_ref SET incref_err_etat='c'" + "WHERE incref_err_numer='" + codeerr + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); this.UpdateEnCours(codeerr, "c", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } case 'm': { this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } default: { this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, ""); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } } } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident."); retour = false; } } } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Systeme en maintenance, pas de remontée d'incidents."); retour = false; } } catch (ClassNotFoundException ex) { acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications."); con.rollback(); acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la connexion."); acgtools_core.AcgIO.SortieLog(ex.getMessage()); retour = false; } catch (SQLException ex) { acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications."); con.rollback(); acgtools_core.AcgIO.SortieLog(ex.getMessage()); acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la requète SQL :"); acgtools_core.AcgIO.SortieLog(RequeteSQL); retour = false; } finally { try { if (statement != null) { statement.close(); } if (retour) { con.commit(); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : succès"); } else { con.rollback(); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : echec"); } if (con != null) { con.close(); } } catch (Exception e) { acgtools_core.AcgIO.SortieLog(new Date() + "Problème lors de la fermeture de la connection à la base de données"); } return retour; } }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
00
|
Code Sample 1:
public static boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; }
Code Sample 2:
private synchronized void resetUserDictionary() { if (this.fChecker == null) return; if (this.fUserDictionary != null) { this.fChecker.removeDictionary(this.fUserDictionary); this.fUserDictionary.unload(); this.fUserDictionary = null; } IPreferenceStore store = SpellActivator.getDefault().getPreferenceStore(); String filePath = store.getString(PreferenceConstants.SPELLING_USER_DICTIONARY); IStringVariableManager variableManager = VariablesPlugin.getDefault().getStringVariableManager(); try { filePath = variableManager.performStringSubstitution(filePath); } catch (CoreException e) { SpellActivator.log(e); return; } if (filePath.length() > 0) { try { File file = new File(filePath); if (!file.exists() && !file.createNewFile()) return; final URL url = new URL("file", null, filePath); InputStream stream = url.openStream(); if (stream != null) { try { this.fUserDictionary = new PersistentSpellDictionary(url); this.fChecker.addDictionary(this.fUserDictionary); } finally { stream.close(); } } } catch (MalformedURLException exception) { } catch (IOException exception) { } } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException(className + "Cannot overwrite existing file: " + dest.getAbsolutePath()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
Code Sample 2:
public static FileChannel getFileChannel(Object o) throws IOException { Class c = o.getClass(); try { Method m = c.getMethod("getChannel", null); return (FileChannel) m.invoke(o, null); } catch (IllegalAccessException x) { } catch (NoSuchMethodException x) { } catch (InvocationTargetException x) { if (x.getTargetException() instanceof IOException) throw (IOException) x.getTargetException(); } if (o instanceof FileInputStream) return new MyFileChannelImpl((FileInputStream) o); if (o instanceof FileOutputStream) return new MyFileChannelImpl((FileOutputStream) o); if (o instanceof RandomAccessFile) return new MyFileChannelImpl((RandomAccessFile) o); Assert.UNREACHABLE(o.getClass().toString()); return null; }
|
11
|
Code Sample 1:
public static List<String> unZip(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream); ZipArchiveEntry entry = in.getNextZipEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextZipEntry(); } in.close(); return result; }
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(); }
|
00
|
Code Sample 1:
public static String fetch(String str_url) throws IOException { URL url; URLConnection connection; String jsonText = ""; url = new URL(str_url); connection = url.openConnection(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { jsonText += line; } return jsonText; }
Code Sample 2:
public void run() { try { URL url = new URL("http://www.sourceforge.net/projects/beobachter/files/beobachter_version.html"); InputStreamReader reader = new InputStreamReader(url.openStream()); BufferedReader buffer = new BufferedReader(reader); String version = buffer.readLine(); buffer.close(); reader.close(); int serverVersion = Integer.valueOf(version.replaceAll("\\.", "")).intValue(); int currentVersion = Integer.valueOf(Constants.APP_VERSION.replaceAll("\\.", "")).intValue(); if (serverVersion > currentVersion) { StringBuilder sb = new StringBuilder(); sb.append(MessageFormat.format(Translator.t("New_version_0_available"), new Object[] { version })).append(Constants.LINE_SEP).append(Constants.LINE_SEP); sb.append(Translator.t("Please_visit_us_on_sourceforge")).append(Constants.LINE_SEP); DialogFactory.showInformationMessage(MainGUI.instance, sb.toString()); } else if (serverVersion <= currentVersion) { DialogFactory.showInformationMessage(MainGUI.instance, Translator.t("There_are_not_updates_available")); } } catch (Exception e) { DialogFactory.showErrorMessage(MainGUI.instance, Translator.t("Unable_to_fetch_server_information")); } }
|
00
|
Code Sample 1:
public URLConnection makeURLConnection(String server) throws IOException { if (server == null) { connection = null; } else { URL url = new URL("http://" + server + "/Bob/QueryXindice"); connection = url.openConnection(); connection.setDoOutput(true); } return connection; }
Code Sample 2:
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
|
11
|
Code Sample 1:
public static byte[] readResource(Class owningClass, String resourceName) { final URL url = getResourceUrl(owningClass, resourceName); if (null == url) { throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName); } LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass); final InputStream inputStream; try { inputStream = url.openStream(); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } return outputStream.toByteArray(); }
Code Sample 2:
public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } }
|
00
|
Code Sample 1:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { String req1xml = jTextArea1.getText(); java.net.URL url = new java.net.URL("http://217.34.8.235:8080/newgenlibctxt/PatronServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println(req1xml); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log.txt"); pw.write(req1xml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(gip)); String reqxml = ""; while (br.ready()) { String line = br.readLine(); reqxml += line; } try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log3.txt"); pw.write(reqxml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } }
Code Sample 2:
public WordEntry[] getVariants(String word) throws MatchPackException { String upperWord = word.toUpperCase(); if (variantsDictionary == null) { try { long start = System.currentTimeMillis(); URL url = this.getClass().getResource("varlex.dic"); ObjectInputStream si = new ObjectInputStream(url.openStream()); variantsDictionary = (Map) si.readObject(); long end = System.currentTimeMillis(); System.out.println("loaded " + (end - start) + "ms"); si.close(); } catch (Exception e) { throw new MatchPackException("cannot load: varlex.dic " + e.getMessage()); } } List l = (List) variantsDictionary.get(upperWord); if (l == null) { return new WordEntry[0]; } return (WordEntry[]) l.toArray(new WordEntry[0]); }
|
00
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public void add(AddInterceptorChain chain, Entry entry, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); PreparedStatement ps = con.prepareStatement("INSERT INTO USERS (id,firstname,lastname,username) VALUES (?,?,?,?)"); ps.setInt(1, 5); ps.setString(2, entry.getEntry().getAttribute(db2ldap.get("firstname")).getStringValue()); ps.setString(3, entry.getEntry().getAttribute(db2ldap.get("lastname")).getStringValue()); ps.setString(4, entry.getEntry().getAttribute(db2ldap.get("username")).getStringValue()); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); PreparedStatement inst = con.prepareStatement("INSERT INTO LOCATIONMAP (person,location) VALUES (?,?)"); LDAPAttribute l = entry.getEntry().getAttribute(db2ldap.get("name")); if (l == null) { con.rollback(); throw new LDAPException("Location is required", LDAPException.OBJECT_CLASS_VIOLATION, "Location is required"); } String[] vals = l.getStringValueArray(); for (int i = 0; i < vals.length; i++) { ps.setString(1, vals[i]); ResultSet rs = ps.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } inst.setInt(1, 5); inst.setInt(2, rs.getInt("id")); inst.executeUpdate(); } ps.close(); inst.close(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not add entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not add entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
|
00
|
Code Sample 1:
protected InputStream makeRequestAndGetJSONData(String url) throws URISyntaxException, ClientProtocolException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); URI uri; InputStream data = null; uri = new URI(url); HttpGet method = new HttpGet(uri); HttpResponse response = httpClient.execute(method); data = response.getEntity().getContent(); return data; }
Code Sample 2:
private HashSet<String> href(String urlstr) throws IOException { HashSet<String> hrefs = new HashSet<String>(); URL url = new URL(urlstr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", "_session_id=" + _session_id); InputStreamReader r = new InputStreamReader(con.getInputStream()); StringWriter b = new StringWriter(); IOUtils.copyTo(r, b); r.close(); try { Thread.sleep(WAIT_SECONDS * 1000); } catch (Exception err) { } String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]"); for (String s1 : tokens) { if (!(s1.startsWith("a") && s1.contains("href"))) continue; String tokens2[] = s1.split("[\\\"\\\']"); for (String s2 : tokens2) { if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue; hrefs.add(s2); } } return hrefs; }
|
00
|
Code Sample 1:
protected Control createContents(Composite parent) { this.getShell().setText("Chisio"); this.getShell().setSize(800, 600); this.getShell().setImage(ImageDescriptor.createFromFile(ChisioMain.class, "icon/chisio-icon.png").createImage()); Composite composite = new Composite(parent, SWT.BORDER); composite.setLayout(new FillLayout()); this.viewer = new ScrollingGraphicalViewer(); this.viewer.setEditDomain(this.editDomain); this.viewer.createControl(composite); this.viewer.getControl().setBackground(ColorConstants.white); this.rootEditPart = new ChsScalableRootEditPart(); this.viewer.setRootEditPart(this.rootEditPart); this.viewer.setEditPartFactory(new ChsEditPartFactory()); ((FigureCanvas) this.viewer.getControl()).setScrollBarVisibility(FigureCanvas.ALWAYS); this.viewer.addDropTargetListener(new ChsFileDropTargetListener(this.viewer, this)); this.viewer.addDragSourceListener(new ChsFileDragSourceListener(this.viewer)); CompoundModel model = new CompoundModel(); model.setAsRoot(); this.viewer.setContents(model); this.viewer.getControl().addMouseListener(this); this.popupManager = new PopupManager(this); this.popupManager.setRemoveAllWhenShown(true); this.popupManager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { ChisioMain.this.popupManager.createActions(manager); } }); KeyHandler keyHandler = new KeyHandler(); ActionRegistry a = new ActionRegistry(); keyHandler.put(KeyStroke.getPressed(SWT.DEL, 127, 0), new DeleteAction(this.viewer)); keyHandler.put(KeyStroke.getPressed('+', SWT.KEYPAD_ADD, 0), new ZoomAction(this, 1, null)); keyHandler.put(KeyStroke.getPressed('-', SWT.KEYPAD_SUBTRACT, 0), new ZoomAction(this, -1, null)); keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), a.getAction(GEFActionConstants.DIRECT_EDIT)); this.viewer.setKeyHandler(keyHandler); this.higlightColor = ColorConstants.yellow; this.createCombos(); return composite; }
Code Sample 2:
public int commit() throws TransactionException, SQLException, ConnectionFactoryException { Connection conn = ConnectionFactoryProxy.getInstance().getConnection(_poolName); conn.setAutoCommit(false); int numRowsUpdated = 0; try { Iterator statements = _statements.iterator(); while (statements.hasNext()) { StatementData sd = (StatementData) statements.next(); PreparedStatement ps = conn.prepareStatement(sd.statement); Iterator params = sd.params.iterator(); int index = 1; while (params.hasNext()) { ps.setString(index++, (String) params.next()); } numRowsUpdated += ps.executeUpdate(); } conn.commit(); } catch (SQLException ex) { System.err.println("com.zenark.zsql.TransactionImpl.commit() failed: Queued Statements follow"); Iterator statements = _statements.iterator(); while (statements.hasNext()) { StatementData sd = (StatementData) statements.next(); System.err.println("+--Statement: " + sd.statement + " with " + sd.params.size() + " parameters"); for (int loop = 0; loop < sd.params.size(); loop++) { System.err.println("+--Param : " + (String) sd.params.get(loop)); } } throw ex; } finally { _statements.clear(); conn.rollback(); conn.clearWarnings(); ConnectionFactoryProxy.getInstance().releaseConnection(conn); } return numRowsUpdated; }
|
11
|
Code Sample 1:
private void serializeWithClass(Class theClass, int count, String comment) { for (int c = 0; c < 10; c++) { if (c == 9) { beginAction(1, "persistence write/read", count, comment); } String tempFile = ".tmp.archive"; SerializeClassInterface theInstance = null; try { theInstance = (SerializeClassInterface) theClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } if (theInstance == null) { System.err.println("error: Couldn't initialize class to " + "be serialized!"); return; } reset(); for (int i = 0; i < count; i++) { try { FileOutputStream fout = new FileOutputStream(tempFile); BufferedOutputStream bout = new BufferedOutputStream(fout); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(theInstance); oout.flush(); oout.close(); } catch (IOException ioe) { System.err.println("serializing: " + tempFile + ":" + ioe.toString()); } try { FileInputStream fin = new FileInputStream(tempFile); BufferedInputStream bin = new BufferedInputStream(fin); ObjectInputStream oin = new ObjectInputStream(bin); theInstance = (SerializeClassInterface) oin.readObject(); oin.close(); } catch (Exception e) { System.err.println("deserializing: " + tempFile + ":" + e.toString()); break; } proceed(); } reset(); if (c == 9) { endAction(); } } }
Code Sample 2:
public MemoryTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } }
|
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 void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
|
00
|
Code Sample 1:
private void loadExample(String resourceFile) { try { URL url = EditorContextMenu.class.getResource(resourceFile); if (this.isDirty()) { if (this.support.saveAs() == JOptionPane.CANCEL_OPTION) { return; } } this.support.loadInputStream(url.openStream()); } catch (IOException ex) { Logger.getLogger(EditorContextMenu.class.getName()).log(Level.SEVERE, null, ex); } }
Code Sample 2:
private Image2D resolvePNG(URI uri) { Image2D image2D = null; if (uri.getScheme() != null) { try { URL url = new URL(uri.toString()); InputStream is = url.openStream(); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (IOException ex) { } } else { String path = uri.getPath(); File file = new File(path); if (file.getAbsoluteFile().exists()) { try { FileInputStream is = new FileInputStream(file); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (FileNotFoundException ex) { } catch (IOException ex) { } } } return image2D; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.