label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: @Test public final void testImportODScontentXml() throws Exception { URL url = ODSTableImporterTest.class.getResource("/Messages.ods_FILES/content.xml"); String systemId = url.getPath(); InputStream in = url.openStream(); ODSTableImporter b = new ODSTableImporter(); b.importODSContentXml(systemId, in, null); assertMessagesOds(b); } Code Sample 2: private 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 AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { InputStream inputStream = null; if (useragent != null) { URLConnection myCon = url.openConnection(); myCon.setUseCaches(false); myCon.setDoInput(true); myCon.setDoOutput(true); myCon.setAllowUserInteraction(false); myCon.setRequestProperty("User-Agent", useragent); myCon.setRequestProperty("Accept", "*/*"); myCon.setRequestProperty("Icy-Metadata", "1"); myCon.setRequestProperty("Connection", "close"); inputStream = new BufferedInputStream(myCon.getInputStream()); } else { inputStream = new BufferedInputStream(url.openStream()); } try { if (DEBUG == true) { System.err.println("Using AppletMpegSPIWorkaround to get codec (AudioFileFormat:url)"); } return getAudioFileFormatForUrl(inputStream); } finally { inputStream.close(); } } Code Sample 2: public void load() throws IOException { File file = new File(filename); URL url = file.toURI().toURL(); Properties temp = new Properties(); temp.load(url.openStream()); if (temp.getProperty("Width") != null) try { width = Integer.valueOf(temp.getProperty("Width")); } catch (Exception e) { System.out.println("Error loading Calibration Sheet Width - leaving as default: " + e); } if (temp.getProperty("Height") != null) try { height = Integer.valueOf(temp.getProperty("Height")); } catch (Exception e) { System.out.println("Error loading Calibration Sheet Height - leaving as default: " + e); } if (temp.getProperty("CircleRadius") != null) try { circleradius = Double.valueOf(temp.getProperty("CircleRadius")); } catch (Exception e) { System.out.println("Error loading Calibration Sheet Circle Radius - leaving as default: " + e); } ArrayList<Ellipse> calibrationcircleslist = new ArrayList<Ellipse>(); int i = 0; while ((temp.getProperty("Circle" + i + "CenterX") != null) && (temp.getProperty("Circle" + i + "CenterY") != null)) { Point2d circlecenter = new Point2d(0, 0); circlecenter.x = Double.valueOf(temp.getProperty("Circle" + i + "CenterX")); circlecenter.y = Double.valueOf(temp.getProperty("Circle" + i + "CenterY")); Ellipse element = new Ellipse(circlecenter, circleradius, circleradius, 0); calibrationcircleslist.add(element); i++; } calibrationcircles = new Ellipse[0]; calibrationcircles = calibrationcircleslist.toArray(calibrationcircles); }
11
Code Sample 1: private void copy(File source, 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); } finally { close(in); close(out); } } Code Sample 2: public void importCertFile(File file) throws IOException { File kd; File cd; synchronized (this) { kd = keysDir; cd = certsDir; } if (!cd.isDirectory()) { kd.mkdirs(); cd.mkdirs(); } String newName = file.getName(); File dest = new File(cd, newName); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(file).getChannel(); destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
11
Code Sample 1: public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } }
00
Code Sample 1: protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); DmsRelationalWord tmpDmsRelationalWord = (DmsRelationalWord) ((DmsRelationalWord) obj).clone(); synchronized (dbConn) { try { Integer nextID = getNextPrimaryID(); Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("INSERT "); sqlStat.append("INTO DMS_RELATIONAL_WORD(ID, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE, WORD, PARENT_ID, TYPE) "); sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, nextID); setPrepareStatement(preStat, 2, tmpDmsRelationalWord.getRecordStatus()); setPrepareStatement(preStat, 3, new Integer(0)); setPrepareStatement(preStat, 4, tmpDmsRelationalWord.getCreatorID()); setPrepareStatement(preStat, 5, currTime); setPrepareStatement(preStat, 6, tmpDmsRelationalWord.getUpdaterID()); setPrepareStatement(preStat, 7, currTime); if (tmpDmsRelationalWord.getWord() == null || "".equals(tmpDmsRelationalWord.getWord().trim())) { return null; } setPrepareStatement(preStat, 8, tmpDmsRelationalWord.getWord()); setPrepareStatement(preStat, 9, tmpDmsRelationalWord.getParentID()); setPrepareStatement(preStat, 10, tmpDmsRelationalWord.getType()); preStat.executeUpdate(); tmpDmsRelationalWord.setID(nextID); tmpDmsRelationalWord.setCreatorID(tmpDmsRelationalWord.getCreatorID()); tmpDmsRelationalWord.setCreateDate(currTime); tmpDmsRelationalWord.setUpdaterID(tmpDmsRelationalWord.getUpdaterID()); tmpDmsRelationalWord.setUpdateDate(currTime); tmpDmsRelationalWord.setUpdateCount(new Integer(0)); tmpDmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getCreatorID())); tmpDmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getUpdaterID())); dbConn.commit(); return (tmpDmsRelationalWord); } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ee) { } log.error(e, e); throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } } Code Sample 2: public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } }
00
Code Sample 1: private void dealWith(String line) throws Exception { if (line.startsWith("#") || (line.length() == 0)) { return; } String sarr[]; sarr = StringUtil.split(line, '\t'); String path = destDir + File.separator + sarr[0]; boolean copyFile = true; if (sarr.length == 2) { try { String serverHash = sarr[1]; String fileHash = loadFileHash(destDir + File.separator + sarr[0]); if (fileHash != null) { if (serverHash.equalsIgnoreCase(fileHash)) { copyFile = false; } else { if (verbose) { System.out.println(" -- " + sarr[0] + " has changed"); } } } } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); System.exit(2); } } if (copyFile) { int idx = path.lastIndexOf('/'); if (idx > 0) { String dir = path.substring(0, idx); File f = new File(dir); f.mkdirs(); } FileOutputStream os = new FileOutputStream(path); byte buf[] = new byte[1024]; URLConnection urc = new URL(urlStr + "/" + sarr[0]).openConnection(); InputStream is = urc.getInputStream(); boolean done = false; while (!done) { int read = is.read(buf, 0, 1024); if (read == -1) { done = true; } else { os.write(buf, 0, read); } } os.close(); is.close(); if (verbose) { System.out.println(" -- Copied: " + sarr[0]); } } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException { log("Retrieving url: " + urlString); DefaultHttpClient httpclient = new DefaultHttpClient(); if (this.archiveAccessSpecification.getUserID() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword())); } HttpGet httpget = new HttpGet(urlString); log("about to do request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); log("-------------- Request results --------------"); log("Status line: " + response.getStatusLine()); if (entity != null) { log("Response content length: " + entity.getContentLength()); } log("contents"); byte[] bytes = null; if (entity != null) { bytes = getBytesFromInputStream(entity.getContent()); entity.consumeContent(); } log("Status code :" + response.getStatusLine().getStatusCode()); log(response.getStatusLine().getReasonPhrase()); if (response.getStatusLine().getStatusCode() != 200) return null; return bytes; } Code Sample 2: public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
11
Code Sample 1: public String upload() throws IOException { int idx = docIndex.incrementAndGet(); String tmpName = "namefinder/doc_" + idx + "__" + fileFileName; File tmpFile = tmpFile(tmpName); if (tmpFile.exists()) { org.apache.commons.io.FileUtils.deleteQuietly(tmpFile); } org.apache.commons.io.FileUtils.touch(tmpFile); InputStream fileStream = new FileInputStream(file); OutputStream bos = new FileOutputStream(tmpFile); IOUtils.copy(fileStream, bos); bos.close(); fileStream.close(); return tmpUrl(tmpName); } Code Sample 2: private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } }
11
Code Sample 1: private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); } Code Sample 2: private static void cut() { File inputFile = new File(inputFileName); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print("Invalid File Name!"); System.err.flush(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.print("Invalid Char Set Name!"); System.err.flush(); System.exit(1); } switch(cutMode) { case charMode: { int outputFileIndex = 1; char[] readBuf = new char[charPerFile]; while (true) { int readCount = 0; try { readCount = in.read(readBuf); } catch (IOException e) { System.err.println("Read IO Error!"); System.err.flush(); System.exit(1); } if (-1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + "-" + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), outputCharSet)); out.write(readBuf, 0, readCount); out.flush(); out.close(); outputFileIndex++; } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } } } break; } case lineMode: { boolean isFileEnd = false; int outputFileIndex = 1; while (!isFileEnd) { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = inputFileName.substring(ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } out.println(line); ++p; } out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } break; } case htmlMode: { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat("0000"); while (!isFileEnd) { try { File outputFile = new File(prefixInputFileName + "-" + df.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); out.println("<html><head><title>" + prefixInputFileName + "-" + df.format(outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } if (line.length() > 0) out.println("<p>" + line + "</p>"); ++p; } out.println("</div><a href=\"" + prefixInputFileName + "-" + df.format(outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } try { File indexFile = new File("index.html"); PrintStream out = new PrintStream(new FileOutputStream(indexFile), false, outputCharSet); out.println("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i++) { out.println("<li><a href=\"" + prefixInputFileName + "-" + df.format(i) + "." + postfixInputFileName + "\">" + df.format(i) + "</a></li>"); } out.println("</ul></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } break; } } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private void copy(File fromFile, File toFile) throws IOException { String fromFileName = fromFile.getName(); File tmpFile = new File(fromFileName); String toFileName = toFile.getName(); if (!tmpFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!tmpFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!tmpFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(tmpFile); File toF = new File(toFile.getCanonicalPath()); if (!toF.exists()) ; toF.createNewFile(); if (!SBCMain.DEBUG_MODE) to = new FileOutputStream(toFile); else to = new FileOutputStream(toF); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } }
00
Code Sample 1: static List<String> listProperties(final MetadataType type) { List<String> props = new ArrayList<String>(); try { File adapter = File.createTempFile("adapter", null); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(type.adapter); if (stream == null) { throw new IllegalStateException("Could not load adapter Jar: " + type.adapter); } FileOutputStream out = new FileOutputStream(adapter); IOUtils.copyLarge(stream, out); out.close(); JarFile jar = new JarFile(adapter); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith("dtd")) { InputStream inputStream = jar.getInputStream(entry); Scanner s = new Scanner(inputStream); while (s.hasNextLine()) { String nextLine = s.nextLine(); if (nextLine.startsWith("<!ELEMENT")) { String prop = nextLine.split(" ")[1]; props.add(prop); } } break; } } } catch (IOException e) { e.printStackTrace(); } return props; } Code Sample 2: public static synchronized Integer getNextSequence(String seqNum) throws ApplicationException { Connection dbConn = null; java.sql.PreparedStatement preStat = null; java.sql.ResultSet rs = null; boolean noTableMatchFlag = false; int currID = 0; int nextID = 0; try { dbConn = getConnection(); } catch (Exception e) { log.error("Error Getting Connection.", e); throw new ApplicationException("errors.framework.db_conn", e); } synchronized (hashPkKeyLock) { if (hashPkKeyLock.get(seqNum) == null) { hashPkKeyLock.put(seqNum, new Object()); } } synchronized (hashPkKeyLock.get(seqNum)) { synchronized (dbConn) { try { preStat = dbConn.prepareStatement("SELECT TABLE_KEY_MAX FROM SYS_TABLE_KEY WHERE TABLE_NAME=?"); preStat.setString(1, seqNum); rs = preStat.executeQuery(); if (rs.next()) { currID = rs.getInt(1); } else { noTableMatchFlag = true; } } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { rs.close(); } catch (Exception ignore) { } finally { rs = null; } try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } if (noTableMatchFlag) { try { currID = 0; preStat = dbConn.prepareStatement("INSERT INTO SYS_TABLE_KEY(TABLE_NAME, TABLE_KEY_MAX) VALUES(?, ?)", java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); preStat.setString(1, seqNum); preStat.setInt(2, currID); preStat.executeUpdate(); } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } try { int updateCnt = 0; nextID = currID; do { nextID++; preStat = dbConn.prepareStatement("UPDATE SYS_TABLE_KEY SET TABLE_KEY_MAX=? WHERE TABLE_NAME=? AND TABLE_KEY_MAX=?", java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); preStat.setInt(1, nextID); preStat.setString(2, seqNum); preStat.setInt(3, currID); updateCnt = preStat.executeUpdate(); currID++; if (updateCnt == 0 && (currID % 2) == 0) { Thread.sleep(50); } } while (updateCnt == 0); dbConn.commit(); return (new Integer(nextID)); } catch (Exception e) { log.error(e, e); try { dbConn.rollback(); } catch (Exception ignore) { } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } } } } }
00
Code Sample 1: public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (queue == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); getQueue().post(eventObj); return eventDoc.getEvent().getEventId(); } Code Sample 2: public static String plainStringToMD5(String input) { if (input == null) { throw new NullPointerException("Input cannot be null"); } MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: public int visitStatement(String statement) throws SQLException { mySQLLogger.info(statement); if (getConnection() == null) { throw new JdbcException("cannot exec: " + statement + ", because 'not connected to database'"); } Statement stmt = getConnection().createStatement(); try { return stmt.executeUpdate(statement); } catch (SQLException ex) { getConnection().rollback(); throw ex; } finally { stmt.close(); } } Code Sample 2: public void appendMessage(MimeMessage oMsg) throws FolderClosedException, StoreClosedException, MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.appendMessage()"); DebugFile.incIdent(); } final String EmptyString = ""; if (!((DBStore) getStore()).isConnected()) { if (DebugFile.trace) DebugFile.decIdent(); throw new StoreClosedException(getStore(), "Store is not connected"); } if (0 == (iOpenMode & READ_WRITE)) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open is READ_WRITE mode"); } if ((0 == (iOpenMode & MODE_MBOX)) && (0 == (iOpenMode & MODE_BLOB))) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open in MBOX nor BLOB mode"); } String gu_mimemsg; if (oMsg.getClass().getName().equals("com.knowgate.hipermail.DBMimeMessage")) { gu_mimemsg = ((DBMimeMessage) oMsg).getMessageGuid(); if (((DBMimeMessage) oMsg).getFolder() == null) ((DBMimeMessage) oMsg).setFolder(this); } else { gu_mimemsg = Gadgets.generateUUID(); } String gu_workarea = ((DBStore) getStore()).getUser().getString(DB.gu_workarea); int iSize = oMsg.getSize(); if (DebugFile.trace) DebugFile.writeln("MimeMessage.getSize() = " + String.valueOf(iSize)); String sContentType, sContentID, sMessageID, sDisposition, sContentMD5, sDescription, sFileName, sEncoding, sSubject, sPriority, sMsgCharSeq; long lPosition = -1; try { sMessageID = oMsg.getMessageID(); if (sMessageID == null || EmptyString.equals(sMessageID)) { try { sMessageID = oMsg.getHeader("X-Qmail-Scanner-Message-ID", null); } catch (Exception ignore) { } } if (sMessageID != null) sMessageID = MimeUtility.decodeText(sMessageID); sContentType = oMsg.getContentType(); if (sContentType != null) sContentType = MimeUtility.decodeText(sContentType); sContentID = oMsg.getContentID(); if (sContentID != null) sContentID = MimeUtility.decodeText(sContentID); sDisposition = oMsg.getDisposition(); if (sDisposition != null) sDisposition = MimeUtility.decodeText(sDisposition); sContentMD5 = oMsg.getContentMD5(); if (sContentMD5 != null) sContentMD5 = MimeUtility.decodeText(sContentMD5); sDescription = oMsg.getDescription(); if (sDescription != null) sDescription = MimeUtility.decodeText(sDescription); sFileName = oMsg.getFileName(); if (sFileName != null) sFileName = MimeUtility.decodeText(sFileName); sEncoding = oMsg.getEncoding(); if (sEncoding != null) sEncoding = MimeUtility.decodeText(sEncoding); sSubject = oMsg.getSubject(); if (sSubject != null) sSubject = MimeUtility.decodeText(sSubject); sPriority = null; sMsgCharSeq = null; } catch (UnsupportedEncodingException uee) { throw new MessagingException(uee.getMessage(), uee); } BigDecimal dPgMessage = null; try { dPgMessage = getNextMessage(); } catch (SQLException sqle) { throw new MessagingException(sqle.getMessage(), sqle); } String sBoundary = getPartsBoundary(oMsg); if (DebugFile.trace) DebugFile.writeln("part boundary is \"" + (sBoundary == null ? "null" : sBoundary) + "\""); if (sMessageID == null) sMessageID = gu_mimemsg; else if (sMessageID.length() == 0) sMessageID = gu_mimemsg; Timestamp tsSent; if (oMsg.getSentDate() != null) tsSent = new Timestamp(oMsg.getSentDate().getTime()); else tsSent = null; Timestamp tsReceived; if (oMsg.getReceivedDate() != null) tsReceived = new Timestamp(oMsg.getReceivedDate().getTime()); else tsReceived = new Timestamp(new java.util.Date().getTime()); try { String sXPriority = oMsg.getHeader("X-Priority", null); if (sXPriority == null) sPriority = null; else { sPriority = ""; for (int x = 0; x < sXPriority.length(); x++) { char cAt = sXPriority.charAt(x); if (cAt >= (char) 48 || cAt <= (char) 57) sPriority += cAt; } sPriority = Gadgets.left(sPriority, 10); } } catch (MessagingException msge) { if (DebugFile.trace) DebugFile.writeln("MessagingException " + msge.getMessage()); } boolean bIsSpam = false; try { String sXSpam = oMsg.getHeader("X-Spam-Flag", null); if (sXSpam != null) bIsSpam = (sXSpam.toUpperCase().indexOf("YES") >= 0 || sXSpam.toUpperCase().indexOf("TRUE") >= 0 || sXSpam.indexOf("1") >= 0); } catch (MessagingException msge) { if (DebugFile.trace) DebugFile.writeln("MessagingException " + msge.getMessage()); } if (DebugFile.trace) DebugFile.writeln("MimeMessage.getFrom()"); Address[] aFrom = null; try { aFrom = oMsg.getFrom(); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("From AddressException " + adre.getMessage()); } InternetAddress oFrom; if (aFrom != null) { if (aFrom.length > 0) oFrom = (InternetAddress) aFrom[0]; else oFrom = null; } else oFrom = null; if (DebugFile.trace) DebugFile.writeln("MimeMessage.getReplyTo()"); Address[] aReply = null; InternetAddress oReply; try { aReply = oMsg.getReplyTo(); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("Reply-To AddressException " + adre.getMessage()); } if (aReply != null) { if (aReply.length > 0) oReply = (InternetAddress) aReply[0]; else oReply = null; } else { if (DebugFile.trace) DebugFile.writeln("no reply-to address found"); oReply = null; } if (DebugFile.trace) DebugFile.writeln("MimeMessage.getRecipients()"); Address[] oTo = null; Address[] oCC = null; Address[] oBCC = null; try { oTo = oMsg.getRecipients(MimeMessage.RecipientType.TO); oCC = oMsg.getRecipients(MimeMessage.RecipientType.CC); oBCC = oMsg.getRecipients(MimeMessage.RecipientType.BCC); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("Recipient AddressException " + adre.getMessage()); } Properties pFrom = new Properties(), pTo = new Properties(), pCC = new Properties(), pBCC = new Properties(); if (DebugFile.trace) DebugFile.writeln("MimeMessage.getFlags()"); Flags oFlgs = oMsg.getFlags(); if (oFlgs == null) oFlgs = new Flags(); MimePart oText = null; ByteArrayOutputStream byOutStrm = null; File oFile = null; MboxFile oMBox = null; if ((iOpenMode & MODE_MBOX) != 0) { try { if (DebugFile.trace) DebugFile.writeln("new File(" + Gadgets.chomp(sFolderDir, File.separator) + oCatg.getStringNull(DB.nm_category, "null") + ".mbox)"); oFile = getFile(); lPosition = oFile.length(); if (DebugFile.trace) DebugFile.writeln("message position is " + String.valueOf(lPosition)); oMBox = new MboxFile(oFile, MboxFile.READ_WRITE); if (DebugFile.trace) DebugFile.writeln("new ByteArrayOutputStream(" + String.valueOf(iSize > 0 ? iSize : 16000) + ")"); byOutStrm = new ByteArrayOutputStream(iSize > 0 ? iSize : 16000); oMsg.writeTo(byOutStrm); sMsgCharSeq = byOutStrm.toString("ISO8859_1"); byOutStrm.close(); } catch (IOException ioe) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(ioe.getMessage(), ioe); } } try { if (oMsg.getClass().getName().equals("com.knowgate.hipermail.DBMimeMessage")) oText = ((DBMimeMessage) oMsg).getBody(); else { oText = new DBMimeMessage(oMsg).getBody(); } if (DebugFile.trace) DebugFile.writeln("ByteArrayOutputStream byOutStrm = new ByteArrayOutputStream(" + oText.getSize() + ")"); byOutStrm = new ByteArrayOutputStream(oText.getSize() > 0 ? oText.getSize() : 8192); oText.writeTo(byOutStrm); if (null == sContentMD5) { MD5 oMd5 = new MD5(); oMd5.Init(); oMd5.Update(byOutStrm.toByteArray()); sContentMD5 = Gadgets.toHexString(oMd5.Final()); oMd5 = null; } } catch (IOException ioe) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("IOException " + ioe.getMessage(), ioe); } catch (OutOfMemoryError oom) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("OutOfMemoryError " + oom.getMessage()); } String sSQL = "INSERT INTO " + DB.k_mime_msgs + "(gu_mimemsg,gu_workarea,gu_category,id_type,id_content,id_message,id_disposition,len_mimemsg,tx_md5,de_mimemsg,file_name,tx_encoding,tx_subject,dt_sent,dt_received,tx_email_from,nm_from,tx_email_reply,nm_to,id_priority,bo_answered,bo_deleted,bo_draft,bo_flagged,bo_recent,bo_seen,bo_spam,pg_message,nu_position,by_content) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); PreparedStatement oStmt = null; try { oStmt = oConn.prepareStatement(sSQL); oStmt.setString(1, gu_mimemsg); oStmt.setString(2, gu_workarea); if (oCatg.isNull(DB.gu_category)) oStmt.setNull(3, Types.CHAR); else oStmt.setString(3, oCatg.getString(DB.gu_category)); oStmt.setString(4, Gadgets.left(sContentType, 254)); oStmt.setString(5, Gadgets.left(sContentID, 254)); oStmt.setString(6, Gadgets.left(sMessageID, 254)); oStmt.setString(7, Gadgets.left(sDisposition, 100)); if ((iOpenMode & MODE_MBOX) != 0) { iSize = sMsgCharSeq.length(); oStmt.setInt(8, iSize); } else { if (iSize >= 0) oStmt.setInt(8, iSize); else oStmt.setNull(8, Types.INTEGER); } oStmt.setString(9, Gadgets.left(sContentMD5, 32)); oStmt.setString(10, Gadgets.left(sDescription, 254)); oStmt.setString(11, Gadgets.left(sFileName, 254)); oStmt.setString(12, Gadgets.left(sEncoding, 16)); oStmt.setString(13, Gadgets.left(sSubject, 254)); oStmt.setTimestamp(14, tsSent); oStmt.setTimestamp(15, tsReceived); if (null == oFrom) { oStmt.setNull(16, Types.VARCHAR); oStmt.setNull(17, Types.VARCHAR); } else { oStmt.setString(16, Gadgets.left(oFrom.getAddress(), 254)); oStmt.setString(17, Gadgets.left(oFrom.getPersonal(), 254)); } if (null == oReply) oStmt.setNull(18, Types.VARCHAR); else oStmt.setString(18, Gadgets.left(oReply.getAddress(), 254)); Address[] aRecipients; String sRecipientName; aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.TO); if (null != aRecipients) if (aRecipients.length == 0) aRecipients = null; if (null != aRecipients) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else { aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.CC); if (null != aRecipients) { if (aRecipients.length > 0) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else oStmt.setNull(19, Types.VARCHAR); } else { aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.BCC); if (null != aRecipients) { if (aRecipients.length > 0) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else oStmt.setNull(19, Types.VARCHAR); } else { oStmt.setNull(19, Types.VARCHAR); } } } if (null == sPriority) oStmt.setNull(20, Types.VARCHAR); else oStmt.setString(20, sPriority); if (oConn.getDataBaseProduct() == JDCConnection.DBMS_ORACLE) { if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBigDecimal(21, ...)"); oStmt.setBigDecimal(21, new BigDecimal(oFlgs.contains(Flags.Flag.ANSWERED) ? "1" : "0")); oStmt.setBigDecimal(22, new BigDecimal(oFlgs.contains(Flags.Flag.DELETED) ? "1" : "0")); oStmt.setBigDecimal(23, new BigDecimal(0)); oStmt.setBigDecimal(24, new BigDecimal(oFlgs.contains(Flags.Flag.FLAGGED) ? "1" : "0")); oStmt.setBigDecimal(25, new BigDecimal(oFlgs.contains(Flags.Flag.RECENT) ? "1" : "0")); oStmt.setBigDecimal(26, new BigDecimal(oFlgs.contains(Flags.Flag.SEEN) ? "1" : "0")); oStmt.setBigDecimal(27, new BigDecimal(bIsSpam ? "1" : "0")); oStmt.setBigDecimal(28, dPgMessage); if ((iOpenMode & MODE_MBOX) != 0) oStmt.setBigDecimal(29, new BigDecimal(lPosition)); else oStmt.setNull(29, Types.NUMERIC); if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBinaryStream(30, new ByteArrayInputStream(" + String.valueOf(byOutStrm.size()) + "))"); if (byOutStrm.size() > 0) oStmt.setBinaryStream(30, new ByteArrayInputStream(byOutStrm.toByteArray()), byOutStrm.size()); else oStmt.setNull(30, Types.LONGVARBINARY); } else { if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setShort(21, ...)"); oStmt.setShort(21, (short) (oFlgs.contains(Flags.Flag.ANSWERED) ? 1 : 0)); oStmt.setShort(22, (short) (oFlgs.contains(Flags.Flag.DELETED) ? 1 : 0)); oStmt.setShort(23, (short) (0)); oStmt.setShort(24, (short) (oFlgs.contains(Flags.Flag.FLAGGED) ? 1 : 0)); oStmt.setShort(25, (short) (oFlgs.contains(Flags.Flag.RECENT) ? 1 : 0)); oStmt.setShort(26, (short) (oFlgs.contains(Flags.Flag.SEEN) ? 1 : 0)); oStmt.setShort(27, (short) (bIsSpam ? 1 : 0)); oStmt.setBigDecimal(28, dPgMessage); if ((iOpenMode & MODE_MBOX) != 0) oStmt.setBigDecimal(29, new BigDecimal(lPosition)); else oStmt.setNull(29, Types.NUMERIC); if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBinaryStream(30, new ByteArrayInputStream(" + String.valueOf(byOutStrm.size()) + "))"); if (byOutStrm.size() > 0) oStmt.setBinaryStream(30, new ByteArrayInputStream(byOutStrm.toByteArray()), byOutStrm.size()); else oStmt.setNull(30, Types.LONGVARBINARY); } if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); oStmt.close(); oStmt = null; } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(DB.k_mime_msgs + " " + sqle.getMessage(), sqle); } if ((iOpenMode & MODE_BLOB) != 0) { try { byOutStrm.close(); } catch (IOException ignore) { } byOutStrm = null; } try { Object oContent = oMsg.getContent(); if (oContent instanceof MimeMultipart) { try { saveMimeParts(oMsg, sMsgCharSeq, sBoundary, gu_mimemsg, sMessageID, dPgMessage.intValue(), 0); } catch (MessagingException msge) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(msge.getMessage(), msge.getNextException()); } } } catch (Exception xcpt) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException("MimeMessage.getContent() " + xcpt.getMessage(), xcpt); } sSQL = "SELECT " + DB.gu_contact + "," + DB.gu_company + "," + DB.tx_name + "," + DB.tx_surname + "," + DB.tx_surname + " FROM " + DB.k_member_address + " WHERE " + DB.tx_email + "=? AND " + DB.gu_workarea + "=? UNION SELECT " + DB.gu_user + ",'****************************USER'," + DB.nm_user + "," + DB.tx_surname1 + "," + DB.tx_surname2 + " FROM " + DB.k_users + " WHERE (" + DB.tx_main_email + "=? OR " + DB.tx_alt_email + "=?) AND " + DB.gu_workarea + "=?"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); PreparedStatement oAddr = null; try { oAddr = oConn.prepareStatement(sSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet oRSet; InternetAddress oInetAdr; String sTxEmail, sGuCompany, sGuContact, sGuUser, sTxName, sTxSurname1, sTxSurname2, sTxPersonal; if (oFrom != null) { oAddr.setString(1, oFrom.getAddress()); oAddr.setString(2, gu_workarea); oAddr.setString(3, oFrom.getAddress()); oAddr.setString(4, oFrom.getAddress()); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pFrom.put(oFrom.getAddress(), sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pFrom.put(oFrom.getAddress(), "null,null,null"); oRSet.close(); } if (DebugFile.trace) DebugFile.writeln("from count = " + pFrom.size()); if (oTo != null) { for (int t = 0; t < oTo.length; t++) { oInetAdr = (InternetAddress) oTo[t]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pTo.put(sTxEmail, sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pTo.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("to count = " + pTo.size()); if (oCC != null) { for (int c = 0; c < oCC.length; c++) { oInetAdr = (InternetAddress) oCC[c]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pCC.put(sTxEmail, sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pCC.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("cc count = " + pCC.size()); if (oBCC != null) { for (int b = 0; b < oBCC.length; b++) { oInetAdr = (InternetAddress) oBCC[b]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pBCC.put(sTxEmail, sGuContact + "," + sGuCompany); } else pBCC.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("bcc count = " + pBCC.size()); oAddr.close(); sSQL = "INSERT INTO " + DB.k_inet_addrs + " (gu_mimemsg,id_message,tx_email,tp_recipient,gu_user,gu_contact,gu_company,tx_personal) VALUES ('" + gu_mimemsg + "','" + sMessageID + "',?,?,?,?,?,?)"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); oStmt = oConn.prepareStatement(sSQL); java.util.Enumeration oMailEnum; String[] aRecipient; if (!pFrom.isEmpty()) { oMailEnum = pFrom.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pFrom.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "from"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pTo.isEmpty()) { oMailEnum = pTo.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pTo.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "to"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pCC.isEmpty()) { oMailEnum = pCC.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pCC.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "cc"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setString(4, null); oStmt.setString(5, null); } else { oStmt.setString(3, null); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pBCC.isEmpty()) { oMailEnum = pBCC.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pBCC.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "bcc"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); oStmt.executeUpdate(); } } oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iSize) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; if ((iOpenMode & MODE_MBOX) != 0) { if (DebugFile.trace) DebugFile.writeln("MboxFile.appendMessage(" + (oMsg.getContentID() != null ? oMsg.getContentID() : "") + ")"); oMBox.appendMessage(sMsgCharSeq); oMBox.close(); oMBox = null; } if (DebugFile.trace) DebugFile.writeln("Connection.commit()"); oConn.commit(); } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oAddr) oAddr.close(); oAddr = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(sqle.getMessage(), sqle); } catch (IOException ioe) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oAddr) oAddr.close(); oAddr = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(ioe.getMessage(), ioe); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.appendMessage() : " + gu_mimemsg); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
11
Code Sample 1: private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } } Code Sample 2: public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
11
Code Sample 1: private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); } Code Sample 2: public static String[] retrieveFasta(String id) throws Exception { URL url = new URL("http://www.uniprot.org/uniprot/" + id + ".fasta"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String header = reader.readLine(); StringBuffer seq = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { seq.append(line); } reader.close(); String[] first = header.split("OS="); return new String[] { id, first[0].split("\\s")[1], first[1].split("GN=")[0], seq.toString() }; }
00
Code Sample 1: private static String getHashString(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); MessageDigest md; md = MessageDigest.getInstance(algorithm); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] hash = md.digest(); return convertToHex(hash); } Code Sample 2: JcrFile createBody(Part part) throws IOException, MessagingException { JcrFile body = new JcrFile(); body.setName("part"); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); body.setMimeType(part.getContentType()); body.setLastModified(java.util.Calendar.getInstance()); return body; }
11
Code Sample 1: private static File copyJarToPool(File file) { File outFile = new File(RizzToolConstants.TOOL_POOL_FOLDER.getAbsolutePath() + File.separator + file.getName()); if (file != null && file.exists() && file.canRead()) { try { FileChannel inChan = new FileInputStream(file).getChannel(); FileChannel outChan = new FileOutputStream(outFile).getChannel(); inChan.transferTo(0, inChan.size(), outChan); return outFile; } catch (Exception ex) { RizzToolConstants.DEFAULT_LOGGER.error("Exception while copying jar file to tool pool [inFile=" + file.getAbsolutePath() + "] [outFile=" + outFile.getAbsolutePath() + ": " + ex); } } else { RizzToolConstants.DEFAULT_LOGGER.error("Could not copy jar file. File does not exist or can't read file. [inFile=" + file.getAbsolutePath() + "]"); } return null; } Code Sample 2: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public static void main(String[] args) { LogFrame.getInstance(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.trim().startsWith(DEBUG_PARAMETER_NAME + "=")) { properties.put(DEBUG_PARAMETER_NAME, arg.trim().substring(DEBUG_PARAMETER_NAME.length() + 1).trim()); if (properties.getProperty(DEBUG_PARAMETER_NAME).toLowerCase().equals(DEBUG_TRUE)) { DEBUG = true; } } else if (arg.trim().startsWith(MODE_PARAMETER_NAME + "=")) { properties.put(MODE_PARAMETER_NAME, arg.trim().substring(MODE_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(AUTOCONNECT_PARAMETER_NAME + "=")) { properties.put(AUTOCONNECT_PARAMETER_NAME, arg.trim().substring(AUTOCONNECT_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SITE_CONFIG_URL_PARAMETER_NAME + "=")) { properties.put(SITE_CONFIG_URL_PARAMETER_NAME, arg.trim().substring(SITE_CONFIG_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(LOAD_PLUGINS_PARAMETER_NAME + "=")) { properties.put(LOAD_PLUGINS_PARAMETER_NAME, arg.trim().substring(LOAD_PLUGINS_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ONTOLOGY_URL_PARAMETER_NAME + "=")) { properties.put(ONTOLOGY_URL_PARAMETER_NAME, arg.trim().substring(ONTOLOGY_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(REPOSITORY_PARAMETER_NAME + "=")) { properties.put(REPOSITORY_PARAMETER_NAME, arg.trim().substring(REPOSITORY_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ONTOLOGY_TYPE_PARAMETER_NAME + "=")) { properties.put(ONTOLOGY_TYPE_PARAMETER_NAME, arg.trim().substring(ONTOLOGY_TYPE_PARAMETER_NAME.length() + 1).trim()); if (!(properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME).equals(ONTOLOGY_TYPE_RDFXML) || properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME).equals(ONTOLOGY_TYPE_TURTLE) || properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME).equals(ONTOLOGY_TYPE_NTRIPPLES))) System.out.println("WARNING! Unknown ontology type: '" + properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME) + "' (Known types are: '" + ONTOLOGY_TYPE_RDFXML + "', '" + ONTOLOGY_TYPE_TURTLE + "', '" + ONTOLOGY_TYPE_NTRIPPLES + "')"); } else if (arg.trim().startsWith(OWLIMSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(OWLIMSERVICE_URL_PARAMETER_NAME, arg.trim().substring(OWLIMSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_URL_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOC_ID_PARAMETER_NAME + "=")) { properties.put(DOC_ID_PARAMETER_NAME, arg.trim().substring(DOC_ID_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ANNSET_NAME_PARAMETER_NAME + "=")) { properties.put(ANNSET_NAME_PARAMETER_NAME, arg.trim().substring(ANNSET_NAME_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(EXECUTIVE_SERVICE_URL_PARAMETER_NAME + "=")) { properties.put(EXECUTIVE_SERVICE_URL_PARAMETER_NAME, arg.trim().substring(EXECUTIVE_SERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(USER_ID_PARAMETER_NAME + "=")) { properties.put(USER_ID_PARAMETER_NAME, arg.trim().substring(USER_ID_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(USER_PASSWORD_PARAMETER_NAME + "=")) { properties.put(USER_PASSWORD_PARAMETER_NAME, arg.trim().substring(USER_PASSWORD_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(EXECUTIVE_PROXY_FACTORY_PARAMETER_NAME + "=")) { properties.put(EXECUTIVE_PROXY_FACTORY_PARAMETER_NAME, arg.trim().substring(EXECUTIVE_PROXY_FACTORY_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME.length() + 1).trim()); RichUIUtils.setDocServiceProxyFactoryClassname(properties.getProperty(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME)); } else if (arg.trim().startsWith(LOAD_ANN_SCHEMAS_NAME + "=")) { properties.put(LOAD_ANN_SCHEMAS_NAME, arg.trim().substring(LOAD_ANN_SCHEMAS_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SELECT_AS_PARAMETER_NAME + "=")) { properties.put(SELECT_AS_PARAMETER_NAME, arg.trim().substring(SELECT_AS_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SELECT_ANN_TYPES_PARAMETER_NAME + "=")) { properties.put(SELECT_ANN_TYPES_PARAMETER_NAME, arg.trim().substring(SELECT_ANN_TYPES_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ENABLE_ONTOLOGY_EDITOR_PARAMETER_NAME + "=")) { properties.put(ENABLE_ONTOLOGY_EDITOR_PARAMETER_NAME, arg.trim().substring(ENABLE_ONTOLOGY_EDITOR_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(CLASSES_TO_HIDE_PARAMETER_NAME + "=")) { properties.put(CLASSES_TO_HIDE_PARAMETER_NAME, arg.trim().substring(CLASSES_TO_HIDE_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(CLASSES_TO_SHOW_PARAMETER_NAME + "=")) { properties.put(CLASSES_TO_SHOW_PARAMETER_NAME, arg.trim().substring(CLASSES_TO_SHOW_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ENABLE_APPLICATION_LOG_PARAMETER_NAME + "=")) { properties.put(ENABLE_APPLICATION_LOG_PARAMETER_NAME, arg.trim().substring(ENABLE_APPLICATION_LOG_PARAMETER_NAME.length() + 1).trim()); } else { System.out.println("WARNING! Unknown or undefined parameter: '" + arg.trim() + "'"); } } System.out.println(startupParamsToString()); if (properties.getProperty(MODE_PARAMETER_NAME) == null || (!(properties.getProperty(MODE_PARAMETER_NAME).toLowerCase().equals(POOL_MODE)) && !(properties.getProperty(MODE_PARAMETER_NAME).toLowerCase().equals(DIRECT_MODE)))) { String err = "Mandatory parameter '" + MODE_PARAMETER_NAME + "' must be defined and must have a value either '" + POOL_MODE + "' or '" + DIRECT_MODE + "'.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) == null || properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() == 0) { String err = "Mandatory parameter '" + SITE_CONFIG_URL_PARAMETER_NAME + "' is missing.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } try { String context = System.getProperty(CONTEXT); if (context == null || "".equals(context)) { context = DEFAULT_CONTEXT; } String s = System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { File f = File.createTempFile("foo", ""); String gateHome = f.getParent().toString() + context; f.delete(); System.setProperty(GateConstants.GATE_HOME_PROPERTY_NAME, gateHome); f = new File(System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/plugins"); File f = new File(System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/gate.xml"); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) != null && properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() > 0) { File f = new File(System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME)); if (f.exists()) { f.delete(); } f.getParentFile().mkdirs(); f.createNewFile(); URL url = new URL(properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME)); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream(f); int i = is.read(); while (i != -1) { fos.write(i); i = is.read(); } fos.close(); is.close(); } try { Gate.init(); gate.Main.applyUserPreferences(); } catch (Exception e) { e.printStackTrace(); } s = BASE_PLUGIN_NAME + "," + properties.getProperty(LOAD_PLUGINS_PARAMETER_NAME); System.out.println("Loading plugins: " + s); loadPlugins(s, true); loadAnnotationSchemas(properties.getProperty(LOAD_ANN_SCHEMAS_NAME), true); } catch (Throwable e) { e.printStackTrace(); } MainFrame.getInstance().setVisible(true); MainFrame.getInstance().pack(); if (properties.getProperty(MODE_PARAMETER_NAME).toLowerCase().equals(DIRECT_MODE)) { if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(DOC_ID_PARAMETER_NAME) == null || properties.getProperty(DOC_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + DOC_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(MainFrame.getInstance(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowDocserviceConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToDocservice.getInstance().actionPerformed(null); } } else { ActionShowDocserviceConnectDialog.getInstance().actionPerformed(null); } } else { if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(USER_ID_PARAMETER_NAME) == null || properties.getProperty(USER_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + USER_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(MainFrame.getInstance(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowExecutiveConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToExecutive.getInstance().actionPerformed(null); } } else { ActionShowExecutiveConnectDialog.getInstance().actionPerformed(null); } } }
00
Code Sample 1: private boolean initConnection() { try { if (ftp == null) { ftp = new FTPClient(); serverIP = getServer(); userName = getUserName(); password = getPassword(); } ftp.connect(serverIP); ftp.login(userName, password); return true; } catch (SocketException a_excp) { throw new RuntimeException(a_excp); } catch (IOException a_excp) { throw new RuntimeException(a_excp); } catch (Throwable a_th) { throw new RuntimeException(a_th); } } Code Sample 2: private void postUrl() throws Exception { String authors = ""; for (String auth : plugin.getDescription().getAuthors()) { authors = authors + " " + auth; } authors = authors.trim(); String url = String.format("http://bukkitstats.randomappdev.com/ping.aspx?snam=%s&sprt=%s&shsh=%s&sver=%s&spcnt=%s&pnam=%s&pmcla=%s&paut=%s&pweb=%s&pver=%s", URLEncoder.encode(plugin.getServer().getName(), "UTF-8"), plugin.getServer().getPort(), hash, URLEncoder.encode(Bukkit.getVersion(), "UTF-8"), plugin.getServer().getOnlinePlayers().length, URLEncoder.encode(plugin.getDescription().getName(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getMain(), "UTF-8"), URLEncoder.encode(authors, "UTF-8"), URLEncoder.encode(plugin.getDescription().getWebsite(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getVersion(), "UTF-8")); new URL(url).openConnection().getInputStream(); }
11
Code Sample 1: public static String doPostWithBasicAuthentication(URL url, String username, String password, String parameters, Map<String, String> headers) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(2000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (parameters != null) con.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: private void headinfoThread() { try { URLConnection urlc = resource.url.openConnection(); resource.setFileSize(urlc.getContentLength()); resource.setDate(urlc.getLastModified()); } catch (IOException e) { System.out.println("Error ResourceConnection, downloading headinfo"); System.out.println(e); } } Code Sample 2: public static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
00
Code Sample 1: private static String[] loadDB(String name) throws IOException { URL url = SpecialConstants.class.getResource(name); if (url == null) throw new FileNotFoundException("file " + name + " not found"); InputStream is = url.openStream(); try { InputStreamReader isr = new InputStreamReader(is, "utf8"); BufferedReader br = new BufferedReader(isr); ArrayList<String> entries = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { entries.add(line); } } String[] r = new String[entries.size()]; entries.toArray(r); return r; } finally { is.close(); } } Code Sample 2: public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_ACCOUNT")); pst.setString(1, acc.getName()); pst.setString(2, acc.getAddress()); pst.setInt(3, acc.getCurrency()); pst.setInt(4, acc.getMainContact()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from account"); rs.next(); id = rs.getInt(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 id; }
00
Code Sample 1: public boolean receiveFile(FileDescriptor fileDescriptor) { try { byte[] block = new byte[1024]; int sizeRead = 0; int totalRead = 0; File dir = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dir.exists()) { dir.mkdirs(); } File file = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); if (!file.exists()) { file.createNewFile(); } SSLSocket sslsocket = getFileTransferConectionConnectMode(ServerAdress.getServerAdress()); OutputStream fileOut = new FileOutputStream(file); InputStream dataIn = sslsocket.getInputStream(); while ((sizeRead = dataIn.read(block)) >= 0) { totalRead += sizeRead; fileOut.write(block, 0, sizeRead); propertyChangeSupport.firePropertyChange("fileByte", 0, totalRead); } fileOut.close(); dataIn.close(); sslsocket.close(); if (fileDescriptor.getName().contains(".snapshot")) { try { File fileData = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); File dirData = new File(Constants.PREVAYLER_DATA_DIRETORY + Constants.FILE_SEPARATOR); File destino = new File(dirData, fileData.getName()); boolean success = fileData.renameTo(destino); if (!success) { deleteDir(Constants.DOWNLOAD_DIR); return false; } deleteDir(Constants.DOWNLOAD_DIR); } catch (Exception e) { e.printStackTrace(); } } else { if (Server.isServerOpen()) { FileChannel inFileChannel = new FileInputStream(file).getChannel(); File dirServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getName()); if (!fileServer.exists()) { fileServer.createNewFile(); } inFileChannel.transferTo(0, inFileChannel.size(), new FileOutputStream(fileServer).getChannel()); inFileChannel.close(); } } if (totalRead == fileDescriptor.getSize()) { return true; } } catch (Exception e) { logger.error("Receive File:", e); } return false; } Code Sample 2: public int read(String name) { status = STATUS_OK; try { name = name.trim().toLowerCase(); if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; }
00
Code Sample 1: public URL rawGetURLfromWebID(String id) { try { System.out.println("Resolving id" + id); String resolve = "/webid/ResolverServlet?wpid=MeetingMachine&method=form&uri=" + id + "&href=_[text/url]"; String resolver = "http://webid.hpl.hp.com:5190"; URL url = new URL(resolve + resolver); URLConnection c = url.openConnection(); c.setDoOutput(true); c.setDoInput(true); c.setUseCaches(false); } catch (Exception e) { if (PropertyEventHeap.debug) { PropertyEventHeap.log("rawGetURLfromWebID " + e); } } return null; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private String getPage(String urlString) throws Exception { if (pageBuffer.containsKey(urlString)) return pageBuffer.get(urlString); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = null; StringBuilder page = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException ioe) { logger.warn("Failed to read web page"); } finally { if (in != null) { in.close(); } } return page.toString(); } Code Sample 2: private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException { Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>(); Enumeration providerFiles = classLoader.getResources(resource); if (!providerFiles.hasMoreElements()) { logger.warning("Can't find the resource: " + resource); return pluginClasses; } do { URL url = (URL) providerFiles.nextElement(); InputStream stream = url.openStream(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { continue; } String line; while ((line = reader.readLine()) != null) { int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } line = line.trim(); if (line.length() > 0) { Class pluginClass; try { pluginClass = classLoader.loadClass(line); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e); continue; } if (Plugin.class.isAssignableFrom(pluginClass)) { pluginClasses.add((Class<? extends Plugin>) pluginClass); } else { logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin."); } } } reader.close(); stream.close(); } while (providerFiles.hasMoreElements()); return pluginClasses; }
00
Code Sample 1: public Vector _getSiteNames() { Vector _mySites = new Vector(); boolean gotSites = false; while (!gotSites) { try { URL dataurl = new URL(getDocumentBase(), siteFile); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String S = readme.readLine(); if (S == null) break; StringTokenizer st = new StringTokenizer(S); _mySites.addElement(st.nextToken()); } gotSites = true; } catch (IOException e) { _mySites.removeAllElements(); gotSites = false; } } return (_mySites); } Code Sample 2: static InputStream getUrlStream(String url) throws IOException { System.out.print("getting : " + url + " ... "); long start = System.currentTimeMillis(); URLConnection c = new URL(url).openConnection(); InputStream is = c.getInputStream(); System.out.print((System.currentTimeMillis() - start) + "ms\n"); return is; }
00
Code Sample 1: public void downSync(Vector v) throws SQLException { try { con = allocateConnection(tableName); PreparedStatement update = con.prepareStatement("update cal_Event set owner=?,subject=?,text=?,place=?," + "contactperson=?,startdate=?,enddate=?,starttime=?,endtime=?,allday=?," + "syncstatus=?,dirtybits=? where OId=? and syncstatus=?"); PreparedStatement insert = con.prepareStatement("insert into cal_Event (owner,subject,text,place," + "contactperson,startdate,enddate,starttime,endtime,allday,syncstatus," + "dirtybits) values(?,?,?,?,?,?,?,?,?,?,?,?)"); PreparedStatement insert1 = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "cal_Event", "newoid")); PreparedStatement delete1 = con.prepareStatement("delete from cal_Event_Remind where event=?"); PreparedStatement delete2 = con.prepareStatement("delete from cal_Event where OId=? " + "and (syncstatus=? or syncstatus=?)"); for (int i = 0; i < v.size(); i++) { try { DO = (EventDO) v.elementAt(i); if (DO.getSyncstatus() == INSERT) { insert.setBigDecimal(1, DO.getOwner()); insert.setString(2, DO.getSubject()); insert.setString(3, DO.getText()); insert.setString(4, DO.getPlace()); insert.setString(5, DO.getContactperson()); insert.setDate(6, DO.getStartdate()); insert.setDate(7, DO.getEnddate()); insert.setTime(8, DO.getStarttime()); insert.setTime(9, DO.getEndtime()); insert.setBoolean(10, DO.getAllday()); insert.setInt(11, RESET); insert.setInt(12, RESET); con.executeUpdate(insert, null); con.reset(); rs = con.executeQuery(insert1, null); if (rs.next()) DO.setOId(rs.getBigDecimal("newoid")); con.reset(); } else if (DO.getSyncstatus() == UPDATE) { update.setBigDecimal(1, DO.getOwner()); update.setString(2, DO.getSubject()); update.setString(3, DO.getText()); update.setString(4, DO.getPlace()); update.setString(5, DO.getContactperson()); update.setDate(6, DO.getStartdate()); update.setDate(7, DO.getEnddate()); update.setTime(8, DO.getStarttime()); update.setTime(9, DO.getEndtime()); update.setBoolean(10, DO.getAllday()); update.setInt(11, RESET); update.setInt(12, RESET); update.setBigDecimal(13, DO.getOId()); update.setInt(14, RESET); con.executeUpdate(update, null); con.reset(); } else if (DO.getSyncstatus() == DELETE) { try { con.setAutoCommit(false); delete1.setBigDecimal(1, DO.getOId()); con.executeUpdate(delete1, null); delete2.setBigDecimal(1, DO.getOId()); delete2.setInt(2, RESET); delete2.setInt(3, DELETE); if (con.executeUpdate(delete2, null) < 1) { con.rollback(); } else { con.commit(); } } catch (Exception e) { con.rollback(); throw e; } finally { con.reset(); } } } catch (Exception e) { if (DO != null) logError("Sync-EventDO.owner = " + DO.getOwner().toString() + " oid = " + (DO.getOId() != null ? DO.getOId().toString() : "NULL"), e); } } if (rs != null) { rs.close(); } } catch (SQLException e) { if (DEBUG) logError("", e); throw e; } finally { release(); } } Code Sample 2: public void testStreamURL() throws Exception { boolean ok = false; String url = "http://www.apache.org/dist/lucene/solr/"; String txt = null; try { txt = IOUtils.toString(new URL(url).openStream()); } catch (Exception ex) { fail("this test only works if you have a network connection."); return; } SolrCore core = h.getCore(); Map<String, String[]> args = new HashMap<String, String[]>(); args.put(CommonParams.STREAM_URL, new String[] { url }); List<ContentStream> streams = new ArrayList<ContentStream>(); parser.buildRequestFrom(core, new MultiMapSolrParams(args), streams); assertEquals(1, streams.size()); assertEquals(txt, IOUtils.toString(streams.get(0).getStream())); }
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: 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); } }
11
Code Sample 1: private static boolean prepareQualifyingFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "qualifying.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line.substring(0, line.indexOf(","))).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } Code Sample 2: protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } }
00
Code Sample 1: public static InputStream getNotCacheResourceAsStream(final String fileName) { if ((fileName.indexOf("file:") >= 0) || (fileName.indexOf(":/") > 0)) { try { URL url = new URL(fileName); return new BufferedInputStream(url.openStream()); } catch (Exception e) { return null; } } return new ByteArrayInputStream(getNotCacheResource(fileName).getData()); } Code Sample 2: protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
11
Code Sample 1: public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } } Code Sample 2: public static void copyFile(final File source, final File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
11
Code Sample 1: protected byte[] computeHash() { try { final MessageDigest inputHash = MessageDigest.getInstance("SHA"); inputHash.update(bufferFileData().getBytes()); return inputHash.digest(); } catch (final NoSuchAlgorithmException nsae) { lastException = nsae; return new byte[0]; } catch (final IOException ioe) { lastException = ioe; return new byte[0]; } } Code Sample 2: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
00
Code Sample 1: public InetSocketAddress getServerAddress() throws IOException { URL url = new URL(ADDRESS_SERVER_URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoOutput(true); con.setReadTimeout(2000); con.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = rd.readLine(); if (line == null) throw new IOException("Cannot read address from address server"); String addr[] = line.split(" ", 2); return new InetSocketAddress(addr[0], Integer.valueOf(addr[1])); } Code Sample 2: public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); }
00
Code Sample 1: private static String getData(String myurl) throws Exception { System.out.println("getdata"); URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { System.out.println(temp); k += temp; } br.close(); return k; } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: private void translate(String sender, String message) { StringTokenizer st = new StringTokenizer(message, " "); message = message.replaceFirst(st.nextToken(), ""); String typeCode = st.nextToken(); message = message.replaceFirst(typeCode, ""); try { String data = URLEncoder.encode(message, "UTF-8"); URL url = new URL("http://babelfish.altavista.com/babelfish/tr?doit=done&urltext=" + data + "&lp=" + typeCode); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.contains("input type=hidden name=\"q\"")) { String[] tokens = line.split("\""); sendMessage(sender, tokens[3]); } } wr.close(); rd.close(); } catch (Exception e) { } } Code Sample 2: public static void main(String[] a) throws Exception { HashMap<String, Integer> numberOfOccurencesOfThisComboe = new HashMap<String, Integer>(); HashMap<String, String> fileToCATHMapping = new HashMap<String, String>(); ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; String reducedComboForFilteringOut = allEntries[1] + allEntries[2] + allEntries[3]; fileToCATHMapping.put(fileName, reducedComboForFilteringOut); if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } for (String fileName : allFilesToBeCopied) { String reducedComboForFilteringOut = fileToCATHMapping.get(fileName); if (!numberOfOccurencesOfThisComboe.containsKey(reducedComboForFilteringOut)) { numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, 1); } else { Integer thisCounter = numberOfOccurencesOfThisComboe.get(reducedComboForFilteringOut); thisCounter = thisCounter + 1; numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, thisCounter); } } HashSet<String> isSingleElement = new HashSet<String>(); for (Entry<String, Integer> thisEntry : numberOfOccurencesOfThisComboe.entrySet()) { if (thisEntry.getValue() == 1) { System.out.println("single: " + thisEntry.getKey()); isSingleElement.add(thisEntry.getKey()); } else { System.out.println("not single: " + thisEntry.getKey()); } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { if (!isSingleElement.contains(fileToCATHMapping.get(file))) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
11
Code Sample 1: public static boolean makeBackup(File dir, String sourcedir, String destinationdir, String destinationDirEnding, boolean autoInitialized) { boolean success = false; String[] files; files = dir.list(); File checkdir = new File(destinationdir + System.getProperty("file.separator") + destinationDirEnding); if (!checkdir.isDirectory()) { checkdir.mkdir(); } ; Date date = new Date(); long msec = date.getTime(); checkdir.setLastModified(msec); try { for (int i = 0; i < files.length; i++) { File f = new File(dir, files[i]); File g = new File(files[i]); if (f.isDirectory()) { } else if (f.getName().endsWith("saving")) { } else { if (f.canRead()) { String destinationFile = checkdir + System.getProperty("file.separator") + g; String sourceFile = sourcedir + System.getProperty("file.separator") + g; FileInputStream infile = new FileInputStream(sourceFile); FileOutputStream outfile = new FileOutputStream(destinationFile); int c; while ((c = infile.read()) != -1) outfile.write(c); infile.close(); outfile.close(); } else { System.out.println(f.getName() + " is LOCKED!"); while (!f.canRead()) { } String destinationFile = checkdir + System.getProperty("file.separator") + g; String sourceFile = sourcedir + System.getProperty("file.separator") + g; FileInputStream infile = new FileInputStream(sourceFile); FileOutputStream outfile = new FileOutputStream(destinationFile); int c; while ((c = infile.read()) != -1) outfile.write(c); infile.close(); outfile.close(); } } } success = true; } catch (Exception e) { success = false; e.printStackTrace(); } if (autoInitialized) { Display display = View.getDisplay(); if (display != null || !display.isDisposed()) { View.getDisplay().syncExec(new Runnable() { public void run() { Tab4.redrawBackupTable(); } }); } return success; } else { View.getDisplay().syncExec(new Runnable() { public void run() { StatusBoxUtils.mainStatusAdd(" Backup Complete", 1); View.getPluginInterface().getPluginconfig().setPluginParameter("Azcvsupdater_last_backup", Time.getCurrentTime(View.getPluginInterface().getPluginconfig().getPluginBooleanParameter("MilitaryTime"))); Tab4.lastBackupTime = View.getPluginInterface().getPluginconfig().getPluginStringParameter("Azcvsupdater_last_backup"); if (Tab4.lastbackupValue != null || !Tab4.lastbackupValue.isDisposed()) { Tab4.lastbackupValue.setText("Last backup: " + Tab4.lastBackupTime); } Tab4.redrawBackupTable(); Tab6Utils.refreshLists(); } }); return success; } } Code Sample 2: public static void copyFile(String f_in, String f_out, boolean remove) throws FileNotFoundException, IOException { if (remove) { PogoString readcode = new PogoString(PogoUtil.readFile(f_in)); readcode = PogoUtil.removeLogMessages(readcode); PogoUtil.writeFile(f_out, readcode.str); } else { FileInputStream fid = new FileInputStream(f_in); FileOutputStream fidout = new FileOutputStream(f_out); int nb = fid.available(); byte[] inStr = new byte[nb]; if (fid.read(inStr) > 0) fidout.write(inStr); fid.close(); fidout.close(); } }
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 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 in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public HttpURLHandler(URL url, String requestMethod, Map<String, String> parameters, String outputEncoding) throws IOException { logger.debug("Creating http url handler for: " + url + "; using method: " + requestMethod + "; with parameters: " + parameters); if (url == null) throw new IllegalArgumentException("Null pointer in url"); if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) throw new IllegalArgumentException("Illegal url protocol: \"" + url.getProtocol() + "\"; must be \"http\" or \"https\""); if (requestMethod == null) throw new IllegalArgumentException("Null pointer in requestMethod"); if (!"GET".equals(requestMethod) && !"POST".equals(requestMethod)) throw new IllegalArgumentException("Illegal request method: " + requestMethod + "; must be \"GET\" or \"POST\""); if (parameters == null) throw new IllegalArgumentException("Null pointer in parameters"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); connection.setRequestMethod(requestMethod); connection.setUseCaches(false); if (EMPTY_MAP.equals(parameters)) { connection.setDoOutput(false); } else { connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); writeParameters(out, parameters, outputEncoding); out.close(); } inputStream = connection.getInputStream(); }
00
Code Sample 1: public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; } Code Sample 2: public static String encrypt(String passPhrase, String password) { String algorithm = "PBEWithMD5AndDES"; byte[] salt = new byte[8]; int iterations = 20; byte[] output = new byte[128]; if (passPhrase == null || "".equals(passPhrase) || password == null || "".equals(password)) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "Required parameter missing"); } try { Security.addProvider(new com.sun.crypto.provider.SunJCE()); KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray()); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); SecretKey secretKey = secretKeyFactory.generateSecret(keySpec); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(passPhrase.getBytes()); byte[] input = new byte[password.length()]; input = password.getBytes(); messageDigest.update(input); byte[] digest = messageDigest.digest(); System.arraycopy(digest, 0, salt, 0, 8); AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(salt, iterations); Cipher cipher = Cipher.getInstance(algorithm); int mode = Cipher.ENCRYPT_MODE; cipher.init(mode, secretKey, algorithmParameterSpec); output = cipher.doFinal(input); } catch (NoSuchAlgorithmException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "Algorithm not found", e); } catch (InvalidAlgorithmParameterException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "nvalidAlgorithmParameter", e); } catch (InvalidKeySpecException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "InvalidKeySpec", e); } catch (InvalidKeyException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "InvalidKey", e); } catch (NoSuchPaddingException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "NoSuchPadding", e); } catch (BadPaddingException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "BadPadding", e); } catch (IllegalBlockSizeException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "IllegalBlockSize", e); } StringBuffer result = new StringBuffer(); for (int i = 0; i < output.length; i++) { result.append(Byte.toString(output[i])); } return result.toString(); }
00
Code Sample 1: public InputStream retrieveStream(String url) { HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); return getResponseEntity.getContent(); } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; } Code Sample 2: public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: MD5AttachHandler::invoke"); try { Message msg = msgContext.getRequestMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope(); org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody(); org.w3c.dom.Element sbElement = sbe.getAsDOM(); org.w3c.dom.Node n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n; String href = paramElement.getAttribute(soapConstants.getAttrHref()); org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils.getActivationDataHandler(ap); org.w3c.dom.Node timeNode = paramElement.getFirstChild(); long startTime = -1; if (timeNode != null && timeNode instanceof org.w3c.dom.Text) { String startTimeStr = ((org.w3c.dom.Text) timeNode).getData(); startTime = Long.parseLong(startTimeStr); } long receivedTime = System.currentTimeMillis(); long elapsedTime = -1; if (startTime > 0) elapsedTime = receivedTime - startTime; String elapsedTimeStr = elapsedTime + ""; java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.io.InputStream attachmentStream = dh.getInputStream(); int bread = 0; byte[] buf = new byte[64 * 1024]; do { bread = attachmentStream.read(buf); if (bread > 0) { md.update(buf, 0, bread); } } while (bread > -1); attachmentStream.close(); buf = null; String contentType = dh.getContentType(); if (contentType != null && contentType.length() != 0) { md.update(contentType.getBytes("US-ASCII")); } sbe = env.getFirstBody(); sbElement = sbe.getAsDOM(); n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; paramElement = (org.w3c.dom.Element) n; String MD5String = org.apache.axis.encoding.Base64.encode(md.digest()); String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String; paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata)); sbe = new org.apache.axis.message.SOAPBodyElement(sbElement); env.clearBody(); env.addBodyElement(sbe); msg = new Message(env); msgContext.setResponseMessage(msg); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } log.debug("Exit: MD5AttachHandler::invoke"); }
11
Code Sample 1: @Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtil.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, null, compareResponse.getControls()); } Code Sample 2: public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); byte[] hash = (new Base64()).encode(raw); return new String(hash); } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } }
00
Code Sample 1: Object execute(String method, Vector params) throws XmlRpcException, IOException { fault = false; long now = 0; if (XmlRpc.debug) { System.err.println("Client calling procedure '" + method + "' with parameters " + params); now = System.currentTimeMillis(); } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); if (buffer == null) { buffer = new ByteArrayOutputStream(); } else { buffer.reset(); } XmlWriter writer = new XmlWriter(buffer); writeRequest(writer, method, params); writer.flush(); byte[] request = buffer.toByteArray(); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); if (auth != null) { con.setRequestProperty("Authorization", "Basic " + auth); } OutputStream out = con.getOutputStream(); out.write(request); out.flush(); out.close(); InputStream in = con.getInputStream(); parse(in); } catch (Exception x) { if (XmlRpc.debug) { x.printStackTrace(); } throw new IOException(x.getMessage()); } if (fault) { XmlRpcException exception = null; try { Hashtable f = (Hashtable) result; String faultString = (String) f.get("faultString"); int faultCode = Integer.parseInt(f.get("faultCode").toString()); exception = new XmlRpcException(faultCode, faultString.trim()); } catch (Exception x) { throw new XmlRpcException(0, "Invalid fault response"); } throw exception; } if (XmlRpc.debug) { System.err.println("Spent " + (System.currentTimeMillis() - now) + " in request"); } return result; } Code Sample 2: public InputPort getInputPort(String file) throws IOException { if (file.equals("/dev/null")) { return new StreamInputPort(new NullInputStream(), file); } URL url = Util.tryURL(file); if (url != null) { return new StreamInputPort(url.openStream(), url.toExternalForm()); } else return new FileInputPort(getFile(file)); }
00
Code Sample 1: private void fetchAlignment() throws IOException { String urlString = BASE_URL + ALN_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); processAlignment(in); } Code Sample 2: public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); }
00
Code Sample 1: protected void downloadFile(String filename, java.io.File targetFile, File partFile, ProgressMonitor monitor) throws java.io.IOException { FileOutputStream out = null; InputStream is = null; try { filename = toCanonicalFilename(filename); URL url = new URL(root + filename.substring(1)); URLConnection urlc = url.openConnection(); int i = urlc.getContentLength(); monitor.setTaskSize(i); out = new FileOutputStream(partFile); is = urlc.getInputStream(); monitor.started(); copyStream(is, out, monitor); monitor.finished(); out.close(); is.close(); if (!partFile.renameTo(targetFile)) { throw new IllegalArgumentException("unable to rename " + partFile + " to " + targetFile); } } catch (IOException e) { if (out != null) out.close(); if (is != null) is.close(); if (partFile.exists() && !partFile.delete()) { throw new IllegalArgumentException("unable to delete " + partFile); } throw e; } } Code Sample 2: public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("usage: PutFromFile [properties file] [file with pmpxml]"); throw new IllegalArgumentException("Wrong number of arguments"); } Reader is = new FileReader(args[1]); char[] b = new char[1024]; StringBuffer sb = new StringBuffer(); int n; while ((n = is.read(b)) > 0) { sb.append(b, 0, n); } String test = sb.toString(); System.out.println(test); String strurl = args[0]; String data = "verb=PutRecord&xml=" + URLEncoder.encode(test, "UTF-8"); URL url = new URL(strurl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); }
11
Code Sample 1: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
11
Code Sample 1: public void removeExifTag(File jpegImageFile, File dst) throws IOException, ImageReadException, ImageWriteException { OutputStream os = null; try { TiffOutputSet outputSet = null; IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile); JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; if (null != jpegMetadata) { TiffImageMetadata exif = jpegMetadata.getExif(); if (null != exif) { outputSet = exif.getOutputSet(); } } if (null == outputSet) { IOUtils.copyFileNio(jpegImageFile, dst); return; } { outputSet.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); TiffOutputDirectory exifDirectory = outputSet.getExifDirectory(); if (null != exifDirectory) exifDirectory.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); } os = new FileOutputStream(dst); os = new BufferedOutputStream(os); new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet); os.close(); os = null; } finally { if (os != null) try { os.close(); } catch (IOException e) { } } } Code Sample 2: public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private void retrieveData() { StringBuffer obsBuf = new StringBuffer(); try { URL url = new URL(getProperty("sourceURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String lineIn = null; while ((lineIn = in.readLine()) != null) { if (GlobalProps.DEBUG) { logger.log(Level.FINE, "WebSource retrieveData: " + lineIn); } obsBuf.append(lineIn); } String fmt = getProperty("dataFormat"); if (GlobalProps.DEBUG) { logger.log(Level.FINE, "Raw: " + obsBuf.toString()); } if ("NWS XML".equals(fmt)) { obs = new NWSXmlObservation(obsBuf.toString()); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't connect to: " + getProperty("sourceURL")); if (GlobalProps.DEBUG) { e.printStackTrace(); } } } Code Sample 2: public String encryptLdapPassword(String algorithm) { String sEncrypted = _password; if ((_password != null) && (_password.length() > 0)) { algorithm = Val.chkStr(algorithm); boolean bMD5 = algorithm.equalsIgnoreCase("MD5"); boolean bSHA = algorithm.equalsIgnoreCase("SHA") || algorithm.equalsIgnoreCase("SHA1") || algorithm.equalsIgnoreCase("SHA-1"); if (bSHA || bMD5) { String sAlgorithm = "MD5"; if (bSHA) { sAlgorithm = "SHA"; } try { MessageDigest md = MessageDigest.getInstance(sAlgorithm); md.update(getPassword().getBytes("UTF-8")); sEncrypted = "{" + sAlgorithm + "}" + (new BASE64Encoder()).encode(md.digest()); } catch (NoSuchAlgorithmException e) { sEncrypted = null; e.printStackTrace(System.err); } catch (UnsupportedEncodingException e) { sEncrypted = null; e.printStackTrace(System.err); } } } return sEncrypted; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
00
Code Sample 1: private BufferedReader getReader(final String fileUrl) throws IOException { InputStreamReader reader; try { reader = new FileReader(fileUrl); } catch (FileNotFoundException e) { URL url = new URL(fileUrl); reader = new InputStreamReader(url.openStream()); } return new BufferedReader(reader); } Code Sample 2: protected void registerClasses() throws PrintException { if (!init) { try { Enumeration<URL> somethingToRegister = this.getClass().getClassLoader().getResources("META-INF/" + getClass().getSimpleName() + ".properties"); while (somethingToRegister.hasMoreElements()) { URL url = (URL) somethingToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); try { Class cls = Class.forName(line); cls.newInstance(); log.debug("class " + line + " registered " + url); } catch (ClassNotFoundException e) { log.error("class " + line + " not found " + url, e); } catch (InstantiationException e) { log.error("class " + line + " not found " + url, e); } catch (IllegalAccessException e) { log.error("class " + line + " not found " + url, e); } line = buff.readLine(); } buff.close(); in.close(); } } catch (IOException e) { throw new PrintException(e.getMessage(), e); } init = true; } }
00
Code Sample 1: private void bubbleSort(int values[]) { PerfMonTimer timerOuter = PerfMonTimer.start("SortingTest.bubbleSort"); try { int len = values.length - 1; for (int i = 0; i < len; i++) { for (int j = 0; j < len - i; j++) { if (values[j] > values[j + 1]) { int tmp = values[j]; values[j] = values[j + 1]; values[j + 1] = tmp; } } } } finally { PerfMonTimer.stop(timerOuter); } } Code Sample 2: public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; }
00
Code Sample 1: public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } } Code Sample 2: protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } }
11
Code Sample 1: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: 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) { TestLogger.error(e); } } catch (FileNotFoundException e) { TestLogger.error(e); } }
00
Code Sample 1: private void initStreams() throws IOException { if (audio != null) { audio.close(); } if (url != null) { audio = new OggInputStream(url.openStream()); } else { audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); } } Code Sample 2: public static int executeUpdate(EOAdaptorChannel channel, String sql, boolean autoCommit) throws SQLException { int rowsUpdated; boolean wasOpen = channel.isOpen(); if (!wasOpen) { channel.openChannel(); } Connection conn = ((JDBCContext) channel.adaptorContext()).connection(); try { Statement stmt = conn.createStatement(); try { rowsUpdated = stmt.executeUpdate(sql); if (autoCommit) { conn.commit(); } } catch (SQLException ex) { if (autoCommit) { conn.rollback(); } throw new RuntimeException("Failed to execute the statement '" + sql + "'.", ex); } finally { stmt.close(); } } finally { if (!wasOpen) { channel.closeChannel(); } } return rowsUpdated; }
00
Code Sample 1: public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } } 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) { } } } }
11
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } } Code Sample 2: public static void main(String[] args) { String inFile = "test_data/blobs.png"; String outFile = "ReadWriteTest.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
11
Code Sample 1: public void saveToPackage() { boolean inPackage = false; String className = IconEditor.className; if (!checkPackage()) { JOptionPane.showMessageDialog(this, "No package selected. Aborting.", "Package not selected!", JOptionPane.WARNING_MESSAGE); return; } File iconFile = new File(getPackageFile().getParent() + File.separator + classIcon); File prevIconFile = new File(prevPackagePath + File.separator + classIcon); if ((IconEditor.getClassIcon() == null) || !prevIconFile.exists()) { IconEditor.setClassIcon("default.gif"); } else if (prevIconFile.exists() && (prevIconFile.compareTo(iconFile) != 0)) { FileFuncs.copyImageFile(prevIconFile, iconFile); } ci = new ClassImport(getPackageFile(), packageClassNamesList, packageClassList); for (int i = 0; i < packageClassList.size(); i++) { if (IconEditor.className.equalsIgnoreCase(packageClassList.get(i).getName())) { inPackage = true; classX = 0 - classX; classY = 0 - classY; shapeList.shift(classX, classY); packageClassList.get(i).setBoundingbox(boundingbox); packageClassList.get(i).setDescription(IconEditor.classDescription); if (IconEditor.getClassIcon() == null) { packageClassList.get(i).setIconName("default.gif"); } else { packageClassList.get(i).setIconName(IconEditor.getClassIcon()); } packageClassList.get(i).setIsRelation(IconEditor.classIsRelation); packageClassList.get(i).setName(IconEditor.className); packageClassList.get(i).setPorts(ports); packageClassList.get(i).shiftPorts(classX, classY); packageClassList.get(i).setShapeList(shapeList); if (dbrClassFields != null && dbrClassFields.getRowCount() > 0) { fields.clear(); for (int j = 0; j < dbrClassFields.getRowCount(); j++) { String fieldName = dbrClassFields.getValueAt(j, iNAME); String fieldType = dbrClassFields.getValueAt(j, iTYPE); String fieldValue = dbrClassFields.getValueAt(j, iVALUE); ClassField field = new ClassField(fieldName, fieldType, fieldValue); fields.add(field); } } packageClassList.get(i).setFields(fields); packageClassList.add(packageClassList.get(i)); packageClassList.remove(i); break; } } try { BufferedReader in = new BufferedReader(new FileReader(getPackageFile())); String str; StringBuffer content = new StringBuffer(); while ((str = in.readLine()) != null) { if (inPackage && str.trim().startsWith("<class")) { break; } else if (!inPackage) { if (str.equalsIgnoreCase("</package>")) break; content.append(str + "\n"); } else if (inPackage) content.append(str + "\n"); } if (!inPackage) { content.append(getShapesInXML(false)); } else { for (int i = 0; i < packageClassList.size(); i++) { classX = 0; classY = 0; makeClass(packageClassList.get(i)); content.append(getShapesInXML(false)); } } content.append("</package>"); in.close(); File javaFile = new File(getPackageFile().getParent() + File.separator + className + ".java"); File prevJavaFile = new File(prevPackagePath + File.separator + className + ".java"); int overwriteFile = JOptionPane.YES_OPTION; if (javaFile.exists()) { overwriteFile = JOptionPane.showConfirmDialog(null, "Java class already exists. Overwrite?"); } if (overwriteFile != JOptionPane.CANCEL_OPTION) { FileOutputStream out = new FileOutputStream(new File(getPackageFile().getAbsolutePath())); out.write(content.toString().getBytes()); out.flush(); out.close(); if (overwriteFile == JOptionPane.YES_OPTION) { String fileText = null; if (prevJavaFile.exists()) { fileText = FileFuncs.getFileContents(prevJavaFile); } else { fileText = "class " + className + " {"; fileText += "\n /*@ specification " + className + " {\n"; for (int i = 0; i < dbrClassFields.getRowCount(); i++) { String fieldName = dbrClassFields.getValueAt(i, iNAME); String fieldType = dbrClassFields.getValueAt(i, iTYPE); if (fieldType != null) { fileText += " " + fieldType + " " + fieldName + ";\n"; } } fileText += " }@*/\n \n}"; } FileFuncs.writeFile(javaFile, fileText); } JOptionPane.showMessageDialog(null, "Saved to package: " + getPackageFile().getName(), "Saved", JOptionPane.INFORMATION_MESSAGE); } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
00
Code Sample 1: public static IChemModel readInChI(URL url) throws CDKException { IChemModel chemModel = new ChemModel(); try { IMoleculeSet moleculeSet = new MoleculeSet(); chemModel.setMoleculeSet(moleculeSet); StdInChIParser parser = new StdInChIParser(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (line.toLowerCase().startsWith("inchi=")) { IAtomContainer atc = parser.parseInchi(line); moleculeSet.addAtomContainer(atc); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new CDKException(e.getMessage()); } return chemModel; } Code Sample 2: public final Matrix2D<E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { MatrixIOUtils.closeQuietly(inputStream); } }
00
Code Sample 1: @Test @Ignore public void testToJson() throws IOException { JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper()); BulkOperation op = js.createBulkOperation(createTestData(10000), false); IOUtils.copy(op.getData(), System.out); } Code Sample 2: public static boolean isDicom(URL url) { assert url != null; boolean isDicom = false; BufferedInputStream is = null; try { is = new BufferedInputStream(url.openStream()); is.skip(DICOM_PREAMBLE_SIZE); byte[] buf = new byte[DICM.length]; is.read(buf); if (buf[0] == DICM[0] && buf[1] == DICM[1] && buf[2] == DICM[2] && buf[3] == DICM[3]) { isDicom = true; } } catch (Exception exc) { System.out.println("ImageFactory::isDicom(): exc=" + exc); } finally { if (is != null) { try { is.close(); } catch (Exception exc) { } } } return isDicom; }
00
Code Sample 1: public static IProject CreateJavaProject(String name, IPath classpath) throws CoreException { // Create and Open New Project in Workspace IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject(name); project.create(null); project.open(null); // Add Java Nature to new Project IProjectDescription desc = project.getDescription(); desc.setNatureIds(new String[] { JavaCore.NATURE_ID}); project.setDescription(desc, null); // Get Java Project Object IJavaProject javaProj = JavaCore.create(project); // Set Output Folder IFolder binDir = project.getFolder("bin"); IPath binPath = binDir.getFullPath(); javaProj.setOutputLocation(binPath, null); // Set Project's Classpath IClasspathEntry cpe = JavaCore.newLibraryEntry(classpath, null, null); javaProj.setRawClasspath(new IClasspathEntry[] {cpe}, null); return project; } Code Sample 2: public List<String> loadList(String name) { List<String> ret = new ArrayList<String>(); try { URL url = getClass().getClassLoader().getResource("lists/" + name + ".utf-8"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { ret.add(line); } reader.close(); } catch (IOException e) { showError("No se puede cargar la lista de valores: " + name, e); } return ret; }
00
Code Sample 1: 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); } 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: public String Hash(String plain) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes(), 0, plain.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (Exception ex) { Log.serverlogger.warn("No such Hash algorithm", ex); return ""; } } Code Sample 2: public TapdocContextImpl(Registry registry, FileObject javaDom, List<String> javadocLinks, List<String> libraryLocations, FileObject outputDirectory, List<String> tapdocLinks, DocumentGenerator documentGenerator) { this.registry = registry; this.documentGenerator = documentGenerator; try { if (javaDom == null) { javaDom = outputDirectory.resolveFile("tapdoc-javadom.xml"); } if (!javaDom.exists()) { javaDom.createFile(); javaDom.close(); IOUtils.copy(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><tapdoc-javadom></tapdoc-javadom>"), javaDom.getContent().getOutputStream()); } this.javaDom = javaDom; this.javadocLinks = javadocLinks; this.tapdocLinks = tapdocLinks; this.libraryLocations = libraryLocations; this.outputDirectory = outputDirectory; } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: private void doIt() throws Throwable { GenericDAO<User> dao = DAOFactory.createDAO(User.class); try { final User user = dao.findUniqueByCriteria(Expression.eq("login", login)); if (user == null) throw new IllegalArgumentException("Specified user isn't exist"); if (srcDir.isDirectory() && srcDir.exists()) { final String[] fileList = srcDir.list(new XFilenameFilter() { public boolean accept(XFile dir, String file) { String[] fNArr = file.split("\\."); return (fNArr.length > 1 && (fNArr[fNArr.length - 1].equalsIgnoreCase("map") || fNArr[fNArr.length - 1].equalsIgnoreCase("plt") || fNArr[fNArr.length - 1].equalsIgnoreCase("wpt"))); } }); int pointsCounter = 0; int tracksCounter = 0; int mapsCounter = 0; for (final String fName : fileList) { try { TransactionManager.beginTransaction(); } catch (Throwable e) { logger.error(e); throw e; } final XFile file = new XFile(srcDir, fName); InputStream in = new XFileInputStream(file); try { ArrayList<UserMapOriginal> maps = new ArrayList<UserMapOriginal>(); ArrayList<MapTrackPointsScaleRequest> tracks = new ArrayList<MapTrackPointsScaleRequest>(); final byte[] headerBuf = new byte[1024]; if (in.read(headerBuf) <= 0) continue; final String fileHeader = new String(headerBuf); final boolean isOziWPT = (fileHeader.indexOf("OziExplorer Waypoint File") >= 0); final boolean isOziPLT = (fileHeader.indexOf("OziExplorer Track Point File") >= 0); final boolean isOziMAP = (fileHeader.indexOf("OziExplorer Map Data File") >= 0); final boolean isKML = (fileHeader.indexOf("<kml xmlns=") >= 0); if (isOziMAP || isOziPLT || isOziWPT || isKML) { in.close(); in = new XFileInputStream(file); } else continue; WPTPoint wp; if (isOziWPT) { try { wp = new WPTPointParser(in, "Cp1251").parse(); } catch (Throwable t) { wp = null; } if (wp != null) { Set<WayPointRow> rows = wp.getPoints(); for (WayPointRow row : rows) { final UserMapPoint p = BeanFactory.createUserPoint(row, user); logger.info("point:" + p.getGuid()); } pointsCounter += rows.size(); } } else if (isOziPLT) { PLTTrack plt; try { plt = new PLTTrackParser(in, "Cp1251").parse(); } catch (Throwable t) { plt = null; } if (plt != null) { final UserMapTrack t = BeanFactory.createUserTrack(plt, user); tracks.add(new MapTrackPointsScaleRequest(t)); tracksCounter++; logger.info("track:" + t.getGuid()); } } else if (isOziMAP) { MapProjection projection; MAPParser parser = new MAPParser(in, "Cp1251"); try { projection = parser.parse(); } catch (Throwable t) { projection = null; } if (projection != null && projection.getPoints() != null && projection.getPoints().size() >= 2) { GenericDAO<UserMapOriginal> mapDao = DAOFactory.createDAO(UserMapOriginal.class); final UserMapOriginal mapOriginal = new UserMapOriginal(); mapOriginal.setName(projection.getTitle()); mapOriginal.setUser(user); mapOriginal.setState(UserMapOriginal.State.UPLOAD); mapOriginal.setSubstate(UserMapOriginal.SubState.COMPLETE); MapManager.updateProjection(projection, mapOriginal); final XFile srcFile = new XFile(srcDir, projection.getPath()); if (!srcFile.exists() || !srcFile.isFile()) throw new IllegalArgumentException("file: " + srcFile.getPath() + " not found"); final XFile mapStorage = new XFile(new XFile(Configuration.getInstance().getPrivateMapStorage().toString()), mapOriginal.getGuid()); mapStorage.mkdir(); XFile dstFile = new XFile(mapStorage, mapOriginal.getGuid()); XFileOutputStream out = new XFileOutputStream(dstFile); XFileInputStream inImg = new XFileInputStream(srcFile); IOUtils.copy(inImg, out); out.flush(); out.close(); inImg.close(); mapDao.save(mapOriginal); maps.add(mapOriginal); srcFile.delete(); mapsCounter++; logger.info("map:" + mapOriginal.getGuid()); } } else logger.warn("unsupported file format: " + file.getName()); TransactionManager.commitTransaction(); for (MapTrackPointsScaleRequest track : tracks) { if (track != null) { try { PoolClientInterface pool = PoolFactory.getInstance().getClientPool(); if (pool == null) throw new IllegalStateException("pool not found"); pool.put(track, new StatesStack(new byte[] { 0x00, 0x11 }), GeneralCompleteStrategy.class); } catch (Throwable t) { logger.error(t); } } } } catch (Throwable e) { logger.error("Error importing", e); TransactionManager.rollbackTransaction(); } finally { in.close(); file.delete(); } } logger.info("waypoints: " + pointsCounter + "\ntracks: " + tracksCounter + "\nmaps: " + mapsCounter); } } catch (Throwable e) { logger.error("Error importing", e); } }
11
Code Sample 1: public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException { log.debug("copyLocalFileAsTempFileInExternallyAccessableDir"); File f = this.createTempFileInExternallyAccessableDir(); FileChannel srcChannel = new FileInputStream(localFileRef).getChannel(); FileChannel dstChannel = new FileOutputStream(f).getChannel(); log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef + " to dest-outputStream: " + f.getAbsolutePath()); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath()); return f; } Code Sample 2: private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
11
Code Sample 1: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public static Chunk updateLastSend(Chunk c) throws Exception { DBConnectionManager dbm = null; Connection conn = null; PreparedStatement stmt = null; Chunk ret = null; String SQL = "UPDATE CHUNK SET SENT=? WHERE FILEHASH=? AND STARTOFF=? AND LENGTH=?"; log.debug("update chunk last sent for chunk " + c.getHash() + " startoff " + c.getStartOffset()); try { dbm = DBConnectionManager.getInstance(); conn = dbm.getConnection("satmule"); stmt = conn.prepareStatement(SQL); stmt.setDate(1, new java.sql.Date(c.getLastSend().getTime())); stmt.setString(2, c.getHash()); stmt.setLong(3, c.getStartOffset()); stmt.setLong(4, c.getSize()); stmt.executeUpdate(); conn.commit(); stmt.close(); dbm.freeConnection("satmule", conn); } catch (Exception e) { log.error("Error while updating chunk " + c.getHash() + "offset:" + c.getStartOffset() + "SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (conn == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { conn.rollback(); excep = new Exception("SQL Error : " + SQL + " error: " + e); dbm.freeConnection("satmule", conn); } throw excep; } return ret; } Code Sample 2: public byte[] getCoded(String name, String pass) { byte[] digest = null; if (pass != null && 0 < pass.length()) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(name.getBytes()); md.update(pass.getBytes()); digest = md.digest(); } catch (Exception e) { e.printStackTrace(); digest = null; } } return digest; }
00
Code Sample 1: public void run() { if (data.length() > 0) { String method = getMethod(); String action = getAction(); URL url; try { URL actionURL; URL baseURL = hdoc.getBase(); if (action == null) { String file = baseURL.getFile(); actionURL = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), file); } else actionURL = new URL(baseURL, action); URLConnection connection; if ("post".equalsIgnoreCase(method)) { url = actionURL; connection = url.openConnection(); ((HttpURLConnection) connection).setFollowRedirects(false); XRendererSupport.setCookies(url, connection); connection.setRequestProperty("Accept-Language", "en-us"); connection.setRequestProperty("User-Agent", XRendererSupport.getContext().getUserAgent()); postData(connection, data); XRendererSupport.getContext().getLogger().message(this, "Posted data: {" + data + "}"); } else { url = new URL(actionURL + "?" + data); connection = url.openConnection(); XRendererSupport.setCookies(url, connection); } connection.connect(); in = connection.getInputStream(); URL base = connection.getURL(); XRendererSupport.getCookies(base, connection); XRendererSupport.getContext().getLogger().message(this, "Stream got ok."); JEditorPane c = (JEditorPane) getContainer(); HTMLEditorKit kit = (HTMLEditorKit) c.getEditorKit(); newDoc = (HTMLDocument) kit.createDefaultDocument(); newDoc.putProperty(Document.StreamDescriptionProperty, base); SwingUtilities.invokeLater(new Runnable() { public void run() { XRendererSupport.getContext().getLogger().message(this, "loading..."); loadDocument(); XRendererSupport.getContext().getLogger().message(this, "document loaded..."); } }); } catch (MalformedURLException m) { } catch (IOException e) { } } } Code Sample 2: public void doFTP() throws BuildException { FTPClient ftp = null; try { task.log("Opening FTP connection to " + task.getServer(), Project.MSG_VERBOSE); ftp = new FTPClient(); if (task.isConfigurationSet()) { ftp = FTPConfigurator.configure(ftp, task); } ftp.setRemoteVerificationEnabled(task.getEnableRemoteVerification()); ftp.connect(task.getServer(), task.getPort()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } task.log("connected", Project.MSG_VERBOSE); task.log("logging in to FTP server", Project.MSG_VERBOSE); if ((task.getAccount() != null && !ftp.login(task.getUserid(), task.getPassword(), task.getAccount())) || (task.getAccount() == null && !ftp.login(task.getUserid(), task.getPassword()))) { throw new BuildException("Could not login to FTP server"); } task.log("login succeeded", Project.MSG_VERBOSE); if (task.isBinary()) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (task.isPassive()) { task.log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } if (task.getInitialSiteCommand() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getInitialSiteCommand()); } }, "initial site command: " + task.getInitialSiteCommand()); } if (task.getUmask() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + task.getUmask()); } }, "umask " + task.getUmask()); } if (task.getAction() == FTPTask.MK_DIR) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, task.getRemotedir()); } }, task.getRemotedir()); } else if (task.getAction() == FTPTask.SITE_CMD) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getSiteCommand()); } }, "Site Command: " + task.getSiteCommand()); } else { if (task.getRemotedir() != null) { task.log("changing the remote directory", Project.MSG_VERBOSE); ftp.changeWorkingDirectory(task.getRemotedir()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (task.isNewer() && task.isTimeDiffAuto()) { task.setTimeDiffMillis(getTimeDiff(ftp)); } task.log(FTPTask.ACTION_STRS[task.getAction()] + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { task.log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { } } } }
11
Code Sample 1: private static void downloadFile(String downloadFileName) throws Exception { URL getFileUrl = new URL("http://www.tegsoft.com/Tobe/getFile" + "?tegsoftFileName=" + downloadFileName); URLConnection getFileUrlConnection = getFileUrl.openConnection(); InputStream is = getFileUrlConnection.getInputStream(); String tobeHome = UiUtil.getParameter("RealPath.Context"); OutputStream out = new FileOutputStream(tobeHome + "/setup/" + downloadFileName); IOUtils.copy(is, out); is.close(); out.close(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: protected InputStream createIconType(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { JavaliController.debug(JavaliController.LG_VERBOSE, "Creating iconType"); String cHash = PRM_TYPE + "=" + TP_ICON; String iconName = req.getParameter("iconName"); if (iconName == null) { res.sendError(res.SC_NOT_FOUND); return null; } Locale loc = null; HttpSession sess = req.getSession(false); JavaliSession jsess = null; int menuType = -1; String menuTypeString = req.getParameter(PRM_MENU_TYPE); try { menuType = new Integer(menuTypeString).intValue(); } catch (Exception e) { } if (sess != null) jsess = (JavaliSession) sess.getAttribute(FormConstants.SESSION_BINDING); if (jsess != null && jsess.getUser() != null) loc = jsess.getUser().getLocale(); else if (sess != null) loc = (Locale) sess.getAttribute(FormConstants.LOCALE_BINDING); if (loc == null) loc = Locale.getDefault(); if (menuType == -1) menuType = MENU_TYPE_TEXTICON; String iconText = JavaliResource.getString("icon." + iconName, loc); if (iconText == null) { iconText = req.getParameter(PRM_MENU_NAME); if (iconText == null) iconText = ""; } cHash += ", " + PRM_ICON_NAME + "=" + iconName + ", text=" + iconText + ", menuType=" + menuType; String iconFileName = null; String fontName = req.getParameter(PRM_FONT_NAME); if (fontName == null) { fontName = "Helvetica"; } cHash += "," + PRM_FONT_NAME + "=" + fontName; String fontSizeString = req.getParameter(PRM_FONT_SIZE); int fontSize; try { fontSize = Integer.parseInt(fontSizeString); } catch (NumberFormatException nfe) { fontSize = 12; } cHash += "," + PRM_FONT_SIZE + "=" + fontSize; String fontTypeString = req.getParameter(PRM_FONT_TYPE); int fontType = Font.BOLD; if ("PLAIN".equalsIgnoreCase(fontTypeString)) fontType = Font.PLAIN; if ("BOLD".equalsIgnoreCase(fontTypeString)) fontType = Font.BOLD; if ("ITALIC".equalsIgnoreCase(fontTypeString)) fontType = Font.ITALIC; if ("ITALICBOLD".equalsIgnoreCase(fontTypeString) || "BOLDITALIC".equalsIgnoreCase(fontTypeString) || "BOLD_ITALIC".equalsIgnoreCase(fontTypeString) || "ITALIC_BOLD".equalsIgnoreCase(fontTypeString)) { fontType = Font.ITALIC | Font.BOLD; } cHash += "," + PRM_FONT_TYPE + "=" + fontType; String fontColor = req.getParameter(PRM_FONT_COLOR); if (fontColor == null || fontColor.equals("")) fontColor = "0x000000"; cHash += "," + PRM_FONT_COLOR + "=" + fontColor; String fName = cacheInfo.file(cHash); JavaliController.debug(JavaliController.LG_VERBOSE, "Called for: " + fName); if (fName == null) { JavaliController.debug(JavaliController.LG_VERBOSE, "No cache found for: " + cHash); if (getServletConfig() != null && getServletConfig().getServletContext() != null) { if (iconName != null && iconName.startsWith("/")) iconFileName = getServletConfig().getServletContext().getRealPath(iconName + ".gif"); else iconFileName = getServletConfig().getServletContext().getRealPath("/icons/" + iconName + ".gif"); File iconFile = new File(iconFileName); if (!iconFile.exists()) { JavaliController.debug(JavaliController.LG_VERBOSE, "Could not find: " + iconFileName); res.sendError(res.SC_NOT_FOUND); return null; } iconFileName = iconFile.getAbsolutePath(); JavaliController.debug(JavaliController.LG_VERBOSE, "file: " + iconFileName + " and cHash=" + cHash); } else { JavaliController.debug(JavaliController.LG_VERBOSE, "No ServletConfig=" + getServletConfig() + " or servletContext"); res.sendError(res.SC_NOT_FOUND); return null; } File tmp = File.createTempFile(PREFIX, SUFIX, cacheDir); OutputStream out = new FileOutputStream(tmp); if (menuType == MENU_TYPE_ICON) { FileInputStream in = new FileInputStream(iconFileName); byte buf[] = new byte[2048]; int read = -1; while ((read = in.read(buf)) != -1) out.write(buf, 0, read); } else if (menuType == MENU_TYPE_TEXT) MessageImage.sendAsGIF(MessageImage.makeMessageImage(iconText, fontName, fontSize, fontType, fontColor, false, "0x000000", true), out); else MessageImage.sendAsGIF(MessageImage.makeIconImage(iconFileName, iconText, fontName, fontColor, fontSize, fontType), out); out.close(); cacheInfo.putFile(cHash, tmp); fName = cacheInfo.file(cHash); } return new FileInputStream(new File(cacheDir, fName)); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: @Override public void send() { BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result.append(str); } } catch (ConnectException ce) { logger.error("MockupExecutableCommand excute fail: " + ce.getMessage()); } catch (Exception e) { logger.error("MockupExecutableCommand excute fail: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } } Code Sample 2: private void initialize() { List providers = new ArrayList(); while (this.urls.hasMoreElements()) { URL url = (URL) this.urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { String provider = uncommentLine(line).trim(); if (provider != null && provider.length() > 0) { providers.add(provider); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } this.iterator = providers.iterator(); }
00
Code Sample 1: public static void main(String[] args) { try { FTPClient p = new FTPClient(); p.connect("url"); p.login("login", "pass"); int sendCommand = p.sendCommand("SYST"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PWD"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("NOOP"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PASV"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); p.changeWorkingDirectory("/"); try { printDir(p, "/"); } catch (Exception e) { e.printStackTrace(); } p.logout(); p.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for(int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); }
11
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: private static void prepare() { System.err.println("PREPARING-----------------------------------------"); deleteHome(); InputStream configStream = null; FileOutputStream tempStream = null; try { configStream = AllTests.class.getClassLoader().getResourceAsStream("net/sf/archimede/test/resources/repository.xml"); new File("temp").mkdir(); tempStream = new FileOutputStream(new File("temp/repository.xml")); IOUtils.copy(configStream, tempStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (configStream != null) { configStream.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } String repositoryName = "jackrabbit.repository"; Properties jndiProperties = new Properties(); jndiProperties.put("java.naming.provider.url", "http://sf.net/projects/archimede#1"); jndiProperties.put("java.naming.factory.initial", "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); startupUtil = new StartupJcrUtil(REPOSITORY_HOME, "temp/repository.xml", repositoryName, jndiProperties); startupUtil.init(); }
00
Code Sample 1: public static NSData sendSynchronousRequest(NSMutableURLRequest req, NSHTTPURLResponseHolder resp, NSErrorHolder error) { NSData data = null; URL url = req.URL().xmlvmGetURL(); URLConnection conn; try { conn = url.openConnection(); data = new NSData(conn.getInputStream()); } catch (IOException e) { } return data; } Code Sample 2: public static void main(String argv[]) { try { if (argv.length != 1 && argv.length != 3) { usage(); System.exit(1); } URL url = new URL(argv[0]); URLConnection conn; conn = url.openConnection(); if (conn.getHeaderField("WWW-Authenticate") != null) { auth(conn, argv[1], argv[2]); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) System.out.println(line); } } catch (Exception ex) { ex.printStackTrace(); } }
11
Code Sample 1: protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; } Code Sample 2: private String encryptPassword(String password) throws NoSuchAlgorithmException { MessageDigest encript = MessageDigest.getInstance("MD5"); encript.update(password.getBytes()); byte[] b = encript.digest(); int size = b.length; StringBuffer h = new StringBuffer(size); for (int i = 0; i < size; i++) { h.append(b[i]); } return h.toString(); }
00
Code Sample 1: public static String generateMessageId(String plain) { byte[] cipher = new byte[35]; String messageId = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes()); cipher = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < cipher.length; i++) { String hex = Integer.toHexString(0xff & cipher[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } StringBuffer pass = new StringBuffer(); pass.append(sb.substring(0, 6)); pass.append("H"); pass.append(sb.substring(6, 11)); pass.append("H"); pass.append(sb.substring(11, 21)); pass.append("H"); pass.append(sb.substring(21)); messageId = new String(pass); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return messageId; } Code Sample 2: public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
00
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } Code Sample 2: public static String email_get_public_hash(String email) { try { if (email != null) { email = email.trim().toLowerCase(); CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(email.getBytes()); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); return crc32.getValue() + " " + new String(md5.digest(email.getBytes())); } } catch (Exception e) { } return ""; }
11
Code Sample 1: public static void doIt(String action) { int f = -1; Statement s = null; Connection connection = null; try { init(); log.info("<<< Looking up UserTransaction >>>"); UserTransaction usertransaction = (UserTransaction) context.lookup("java:comp/UserTransaction"); log.info("<<< beginning the transaction >>>"); usertransaction.begin(); log.info("<<< Connecting to xadatasource >>>"); connection = xadatasource.getConnection(); log.info("<<< Connected >>>"); s = connection.createStatement(); s.executeUpdate("update testdata set foo=foo + 1 where id=1"); if ((action != null) && action.equals("commit")) { log.info("<<< committing the transaction >>>"); usertransaction.commit(); } else { log.info("<<< rolling back the transaction >>>"); usertransaction.rollback(); } log.info("<<< transaction complete >>>"); } catch (Exception e) { log.error("doIt", e); } finally { try { s.close(); connection.close(); } catch (Exception x) { log.error("problem closing statement/connection", x); } } } Code Sample 2: public Long createSite(Site site, List<String> hosts) { if (log.isDebugEnabled()) { log.debug("site: " + site); if (site != null) { log.debug(" language: " + site.getDefLanguage()); log.debug(" country: " + site.getDefCountry()); log.debug(" variant: " + site.getDefVariant()); log.debug(" companyId: " + site.getCompanyId()); } } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_PORTAL_LIST_SITE"); seq.setTableName("WM_PORTAL_LIST_SITE"); seq.setColumnName("ID_SITE"); Long siteId = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_PORTAL_LIST_SITE (" + "ID_SITE, ID_FIRM, DEF_LANGUAGE, DEF_COUNTRY, DEF_VARIANT, " + "NAME_SITE, ADMIN_EMAIL, IS_CSS_DYNAMIC, CSS_FILE, " + "IS_REGISTER_ALLOWED " + ")values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, siteId); RsetTools.setLong(ps, num++, site.getCompanyId()); ps.setString(num++, site.getDefLanguage()); ps.setString(num++, site.getDefCountry()); ps.setString(num++, site.getDefVariant()); ps.setString(num++, site.getSiteName()); ps.setString(num++, site.getAdminEmail()); ps.setInt(num++, site.getCssDynamic() ? 1 : 0); ps.setString(num++, site.getCssFile()); ps.setInt(num++, site.getRegisterAllowed() ? 1 : 0); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); if (hosts != null) { for (String s : hosts) { VirtualHost host = new VirtualHostBean(null, siteId, s); InternalDaoFactory.getInternalVirtualHostDao().createVirtualHost(dbDyn, host); } } dbDyn.commit(); return siteId; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new site"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
00
Code Sample 1: public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { throw new RuntimeException("Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("NoSuchAlgorithmException : " + e.getMessage()); } return digest; } Code Sample 2: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } }
00
Code Sample 1: public static String ReadURLStringAndWrite(URL url, String str) throws Exception { String stringToReverse = URLEncoder.encode(str, "UTF-8"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(stringToReverse); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString; String back = ""; while ((decodedString = in.readLine()) != null) { back += decodedString + "\n"; } in.close(); return back; } Code Sample 2: TreeMap<Integer, Integer> initProperties(URL propurl) { String zoneFileName = null; String costFileName = null; String homesFileName = null; String jobsFileName = null; Properties props = new Properties(); try { props.loadFromXML(propurl.openStream()); zoneFileName = props.getProperty("zoneFileName"); costFileName = props.getProperty("costFileName"); homesFileName = props.getProperty("homesFileName"); jobsFileName = props.getProperty("jobsFileName"); maxiter = Integer.parseInt(props.getProperty("maxiter")); mu = Double.parseDouble(props.getProperty("mu")); theta = Double.parseDouble(props.getProperty("theta")); threshold1 = Double.parseDouble(props.getProperty("threshold1")); threshold2 = Double.parseDouble(props.getProperty("threshold2")); verbose = Boolean.parseBoolean(props.getProperty("verbose")); } catch (Exception xc) { xc.printStackTrace(); System.exit(-1); } HashSet<Integer> zoneids = SomeIO.readZoneIDs(zoneFileName); numZ = zoneids.size(); if (verbose) { System.out.println("Data:"); System.out.println(" . #zones:" + numZ); } int idx = 0; TreeMap<Integer, Integer> zonemap = new TreeMap<Integer, Integer>(); for (Integer id : zoneids) zonemap.put(id, idx++); cij = SomeIO.readMatrix(costFileName, numZ, numZ); for (int i = 0; i < numZ; i++) { double mincij = Double.POSITIVE_INFINITY; for (int j = 0; j < numZ; j++) { double v = cij.get(i, j); if ((v < mincij) && (v > 0.0)) mincij = v; } if (cij.get(i, i) == 0.0) cij.set(i, i, mincij); } setupECij(); double meanCost = 0.0; double stdCost = 0.0; for (int i = 0; i < numZ; i++) { for (int j = 0; j < numZ; j++) { double v = cij.get(i, j); meanCost += v; stdCost += v * v; } } meanCost = meanCost / (numZ * numZ); stdCost = stdCost / (numZ * numZ) - meanCost * meanCost; if (verbose) System.out.println(" . Travel costs mean=" + meanCost + " std.dev.= " + Math.sqrt(stdCost)); P = SomeIO.readZoneAttribute(numZ, homesFileName, zonemap); J = SomeIO.readZoneAttribute(numZ, jobsFileName, zonemap); double maxpj = 0.0; double sp = 0.0; double sj = 0.0; for (int i = 0; i < numZ; i++) { sp += P[i]; sj += J[i]; if (P[i] > maxpj) maxpj = P[i]; if (J[i] > maxpj) maxpj = J[i]; } if (Math.abs(sp - sj) > 1.0) { System.err.println("Error: #jobs(" + sj + ")!= #homes(" + sp + ")"); System.exit(-1); } N = sp; if (verbose) System.out.println(" . Trip tables: #jobs=#homes= " + N); return zonemap; }
00
Code Sample 1: public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } } Code Sample 2: public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
11
Code Sample 1: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { tmpFile = File.createTempFile("ftp", "dat", new File("./tmp")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); IOUtils.copy(is, bos); bos.flush(); bos.close(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } } Code Sample 2: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: public static void main(String[] args) throws IOException { System.out.println("Start filtering zgps..."); final Config config = ConfigUtils.loadConfig(args[0]); final String CONFIG_MODULE = "GPSFilterZGPS"; File sourceFileSelectedStages = new File(config.findParam(CONFIG_MODULE, "sourceFileSelectedStages")); File sourceFileZGPS = new File(config.findParam(CONFIG_MODULE, "sourceFileZGPS")); File targetFile = new File(config.findParam(CONFIG_MODULE, "targetFile")); System.out.println("Start reading selected stages..."); FilterZGPSSelectedStages selectedStages = new FilterZGPSSelectedStages(); selectedStages.createSelectedStages(sourceFileSelectedStages); System.out.println("Done. " + selectedStages.getSelectedStages().size() + " stages were stored"); System.out.println("Start reading and writing zgps..."); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileZGPS))); BufferedWriter out = new BufferedWriter(new FileWriter(targetFile)); out.write(in.readLine()); out.newLine(); String lineFromInputFile; while ((lineFromInputFile = in.readLine()) != null) { String[] entries = lineFromInputFile.split("\t"); if (selectedStages.containsStage(Integer.parseInt(entries[0]), Integer.parseInt(entries[1]), Integer.parseInt(entries[2]))) { out.write(lineFromInputFile); out.newLine(); out.flush(); } } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("Could not find source file for selected stages."); e.printStackTrace(); } catch (IOException e) { System.out.println("IO Exception while reading or writing zgps."); e.printStackTrace(); } System.out.println("Done."); } Code Sample 2: protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { LOG.debug("copying file"); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tTempFileName)); Datastream tDatastream = new LocalDatastream(this.getGenericFileName(pDeposit), this.getContentType(), tTempFileName); List<Datastream> tDatastreams = new ArrayList<Datastream>(); tDatastreams.add(tDatastream); return tDatastreams; }
00
Code Sample 1: private String send(String method, String contentType, String urlStr, String body) throws MalformedURLException, IOException { HttpURLConnection postCon = (HttpURLConnection) new URL(getUrl(urlStr)).openConnection(); postCon.setRequestMethod(method); postCon.setDoOutput(true); postCon.setDoInput(true); if (cookie != null) { postCon.setRequestProperty("Cookie", cookie); if (contentType != null) { postCon.setRequestProperty("Content-type", contentType); } postCon.setRequestProperty("Content-Length", body == null ? "0" : Integer.toString(body.length())); } if (body != null) { OutputStream os = postCon.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os); out.write(body); out.close(); } InputStream is = null; try { is = postCon.getInputStream(); } catch (IOException ioe) { is = postCon.getErrorStream(); } int resCode = postCon.getResponseCode(); if (resCode == 201 || resCode == 202) { String loc = postCon.getHeaderField("Location"); System.out.println("loc:" + loc); return loc; } StringBuffer sb = StreamUtil.readStream(is); return sb.toString(); } Code Sample 2: public static String getKeyWithRightLength(final String key, int keyLength) { if (keyLength > 0) { if (key.length() == keyLength) { return key; } else { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return ""; } md.update(key.getBytes()); byte[] hash = md.digest(); if (keyLength > 20) { byte nhash[] = new byte[keyLength]; for (int i = 0; i < keyLength; i++) { nhash[i] = hash[i % 20]; } hash = nhash; } return new String(hash).substring(0, keyLength); } } else { return key; } }
11
Code Sample 1: private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } } Code Sample 2: private static final void cloneFile(File origin, File target) throws IOException { FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(origin).getChannel(); destChannel = new FileOutputStream(target).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) srcChannel.close(); if (destChannel != null) destChannel.close(); } }
11
Code Sample 1: @Override public void render(Output output) throws IOException { output.setStatus(statusCode, statusMessage); if (headersMap != null) { Iterator<Entry<String, String>> iterator = headersMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> header = iterator.next(); output.addHeader(header.getKey(), header.getValue()); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } } Code Sample 2: private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); }
11
Code Sample 1: @JiveScriptCommand(help = "Load and executes a JiveScript file") public void load(String path) throws JiveScriptException, IOException { loading = true; JivesScene.setActiveScene(null); boolean allowScripting = JiveScriptEngine.allowScripting; JiveScriptEngine.allowScripting = true; JiveScriptEngine.FILENAME = null; URL url = new URL(path); InputStream fis = url.openStream(); if (fis == null) { throw new IOException("Unable to open file at path " + path); } BufferedReader br = new BufferedReader(new InputStreamReader(fis)); script = ""; String line; while ((line = br.readLine()) != null) { script = script.concat(line) + Log.LINE_SEPARATOR; } eval(script); if (JiveScriptEngine.FILENAME == null) { String filename = path.substring(path.lastIndexOf(File.separatorChar) + 1); JiveScriptEngine.FILENAME = filename; } JiveScriptEngine.MD5 = DigestUtils.md5Hex(script.toString().getBytes()); NetworkImplementorIntf networkImplementor = Jives.getNetwork(); Object[] config = (Object[]) networkImplementor.getConnectionState(NetworkImplementorIntf.CONNECTIONSTATE_ALL); boolean internet = (Boolean) config[NetworkImplementorIntf.CONNECTIONSTATE_INTERNET]; if (internet) { echo("Starting network on the internet"); } else { boolean ipv6 = (Boolean) config[NetworkImplementorIntf.CONNECTIONSTATE_IPV6]; String connection = (String) config[NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV4] + ":" + (Integer) config[NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV4_PORT]; if (ipv6) { connection = (String) networkImplementor.getConnectionState(NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV6) + ":" + (Integer) networkImplementor.getConnectionState(NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV6_PORT); } echo("Starting network on " + connection); } networkImplementor.startNetwork(JiveScriptEngine.FILENAME, JiveScriptEngine.MD5); fis.close(); if (JiveScriptEngine.allowScripting && !allowScripting) { JiveScriptEngine.allowScripting = allowScripting; } loading = false; } Code Sample 2: private ArrayList<String> loadProperties(String filename) throws DevFailed, IOException { java.net.URL url = getClass().getResource(filename); if (url == null) { Except.throw_exception("LOAD_PROPERTY_FAILED", "URL for property file (" + filename + ") is null !", "PogoProperty.loadProperties()"); return null; } InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ArrayList<String> vs = new ArrayList<String>(); String str; while ((str = br.readLine()) != null) { str = str.trim(); if (!str.startsWith("#")) if (str.length() > 0) vs.add(str); } br.close(); return vs; }
00
Code Sample 1: private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } Code Sample 2: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
11
Code Sample 1: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } } Code Sample 2: @SuppressWarnings("unchecked") protected void processDownloadAction(HttpServletRequest request, HttpServletResponse response) throws Exception { File transformationFile = new File(xslBase, "file-info.xsl"); HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); DataSourceIf dataSource = new NullSource(); Document fileInfoDoc = XmlUtils.getEmptyDOM(); DOMResult result = new DOMResult(fileInfoDoc); transformer.transform((Source) dataSource, result); Element documentElement = fileInfoDoc.getDocumentElement(); if (documentElement.getLocalName().equals("null")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } InputStream is = null; try { XPath xpath = XPathFactory.newInstance().newXPath(); String sourceType = XPathUtils.getStringValue(xpath, "source-type", documentElement, null); String location = XPathUtils.getStringValue(xpath, "location", documentElement, null); String fileName = XPathUtils.getStringValue(xpath, "file-name", documentElement, null); String mimeType = XPathUtils.getStringValue(xpath, "mime-type", documentElement, null); String encoding = XPathUtils.getStringValue(xpath, "encoding", documentElement, null); if (StringUtils.equals(sourceType, "cifsSource")) { String domain = XPathUtils.getStringValue(xpath, "domain", documentElement, null); String userName = XPathUtils.getStringValue(xpath, "username", documentElement, null); String password = XPathUtils.getStringValue(xpath, "password", documentElement, null); URI uri = new URI(location); if (StringUtils.isNotBlank(userName)) { String userInfo = ""; if (StringUtils.isNotBlank(domain)) { userInfo = userInfo + domain + ";"; } userInfo = userInfo + userName; if (StringUtils.isNotBlank(password)) { userInfo = userInfo + ":" + password; } uri = new URI(uri.getScheme(), userInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } SmbFile smbFile = new SmbFile(uri.toURL()); is = new SmbFileInputStream(smbFile); } else if (StringUtils.equals(sourceType, "localFileSystemSource")) { File file = new File(location); is = new FileInputStream(file); } else { logger.error("Source type \"" + ((sourceType != null) ? sourceType : "") + "\" not supported"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (StringUtils.isBlank(mimeType) && StringUtils.isBlank(encoding)) { response.setContentType(Definitions.MIMETYPE_BINARY); } else if (StringUtils.isBlank(encoding)) { response.setContentType(mimeType); } else { response.setContentType(mimeType + ";charset=" + encoding); } if (request.getParameterMap().containsKey(Definitions.REQUEST_PARAMNAME_DOWNLOAD)) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); } IOUtils.copy(new BufferedInputStream(is), response.getOutputStream()); } finally { if (is != null) { is.close(); } } }
00
Code Sample 1: @Override public void run() { handle.start(); handle.switchToIndeterminate(); FacebookJsonRestClient client = new FacebookJsonRestClient(API_KEY, SECRET); client.setIsDesktop(true); HttpURLConnection connection; List<String> cookies; try { String token = client.auth_createToken(); String post_url = "http://www.facebook.com/login.php"; String get_url = "http://www.facebook.com/login.php" + "?api_key=" + API_KEY + "&v=1.0" + "&auth_token=" + token; HttpURLConnection.setFollowRedirects(true); connection = (HttpURLConnection) new URL(get_url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); connection.connect(); cookies = connection.getHeaderFields().get("Set-Cookie"); connection = (HttpURLConnection) new URL(post_url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } String params = "api_key=" + API_KEY + "&auth_token=" + token + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pass=" + URLEncoder.encode(pass, "UTF-8") + "&v=1.0"; connection.setRequestProperty("Content-Length", Integer.toString(params.length())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(params.toString().getBytes("UTF-8")); connection.getOutputStream().close(); cookies = connection.getHeaderFields().get("Set-Cookie"); if (cookies == null) { ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String url = "http://www.chartsy.org/facebook/"; DesktopUtil.browseAndWarn(url, null); } }; NotifyUtil.show("Application Permission", "You need to grant permission first.", MessageType.WARNING, listener, false); connection.disconnect(); loggedIn = false; } else { sessionKey = client.auth_getSession(token); sessionSecret = client.getSessionSecret(); loggedIn = true; } connection.disconnect(); handle.finish(); } catch (FacebookException fex) { handle.finish(); NotifyUtil.error("Login Error", fex.getMessage(), fex, false); } catch (IOException ioex) { handle.finish(); NotifyUtil.error("Login Error", ioex.getMessage(), ioex, false); } } Code Sample 2: public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = DefaultXmlFieldSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; }
00
Code Sample 1: public SpreadSheetFrame(FileManager owner, File file, Delimiter delim) { super(owner, file.getPath()); JPanel pane = new JPanel(new BorderLayout()); super.contentPane.add(pane); this.tableModel = new BigTableModel(file, delim); this.table = new JTable(tableModel); this.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.tableModel.setTable(this.table); pane.add(new JScrollPane(this.table)); addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { tableModel.close(); } }); JMenu menu = new JMenu("Tools"); getJMenuBar().add(menu); menu.add(new AbstractAction("NCBI") { @Override public void actionPerformed(ActionEvent e) { try { Pattern delim = Pattern.compile("[ ]"); BufferedReader r = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("/home/lindenb/jeter.txt.gz")))); String line = null; URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("db=snp&retmode=xml"); while ((line = r.readLine()) != null) { String tokens[] = delim.split(line, 2); if (!tokens[0].startsWith("rs")) continue; wr.write("&id=" + tokens[0].substring(2).trim()); } wr.flush(); r.close(); InputStream in = conn.getInputStream(); IOUtils.copyTo(in, System.err); in.close(); wr.close(); } catch (IOException err) { err.printStackTrace(); } } }); } Code Sample 2: public void excluirTopico(Integer idDisciplina) throws Exception { String sql = "DELETE from topico WHERE id_disciplina = ?"; PreparedStatement stmt = null; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, idDisciplina); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
00
Code Sample 1: public void setPage(String url) { System.out.println("SetPage(" + url + ")"); if (url != null) { if (!url.startsWith("http://")) { url = "http://" + url; } boolean exists = false; for (int i = 0; i < urlComboBox.getItemCount(); i++) { if (((String) urlComboBox.getItemAt(i)).equals(url)) { exists = true; urlComboBox.setSelectedItem(url); } } if (!exists) { int i = urlComboBox.getSelectedIndex(); if (i == -1 || urlComboBox.getItemCount() == 0) { i = 0; } else { i++; } urlComboBox.insertItemAt(url, i); urlComboBox.setSelectedItem(url); } boolean image = false; for (final String element : imageExtensions) { if (url.endsWith(element)) { image = true; } } try { if (image) { final String html = "<html><img src=\"" + url + "\"></html>"; } else { final String furl = url; Runnable loadPage = new Runnable() { public void run() { try { System.out.println("Setting page on Cobra"); SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext()); int nodeBaseEnd = furl.indexOf("/", 10); if (nodeBaseEnd == -1) nodeBaseEnd = furl.length(); String nodeBase = furl.substring(0, nodeBaseEnd); InputStream pageStream = new URL(furl).openStream(); BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream)); String pageContent = ""; String line; while ((line = pageStreamReader.readLine()) != null) pageContent += line; pageContent = borderImages(pageContent, nodeBase); htmlPanel.setHtml(pageContent, furl, rendererContext); } catch (Exception e) { System.out.println("Error loading page " + furl + " : " + e); } } }; new Thread(loadPage).start(); } } catch (final Throwable exception) { System.out.println("Error in Browser.setPage(): " + exception); } } } Code Sample 2: public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
11
Code Sample 1: public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } } Code Sample 2: private static void exportConfigResource(ClassLoader classLoader, String resourceName, String targetFileName) throws Exception { InputStream is = classLoader.getResourceAsStream(resourceName); FileOutputStream fos = new FileOutputStream(targetFileName, false); IOUtils.copy(is, fos); fos.close(); is.close(); }
11
Code Sample 1: public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } } Code Sample 2: private Tuple execute(final HttpMethodBase method, int numTries) throws IOException { final Timer timer = Metric.newTimer("RestClientImpl.execute"); try { final int sc = httpClient.executeMethod(method); if (sc < OK_MIN || sc > OK_MAX) { throw new RestException("Unexpected status code: " + sc + ": " + method.getStatusText() + " -- " + method, sc); } final InputStream in = method.getResponseBodyAsStream(); try { final StringWriter writer = new StringWriter(2048); IOUtils.copy(in, writer, method.getResponseCharSet()); return new Tuple(sc, writer.toString()); } finally { in.close(); } } catch (NullPointerException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (SocketException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (IOException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw e; } finally { method.releaseConnection(); timer.stop(); } }
00
Code Sample 1: public static String encrypt(String plaintext) throws EncryptionException { if (plaintext == null) { throw new EncryptionException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); return Base64.encodeBytes(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } } Code Sample 2: public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
11
Code Sample 1: public stock(String ticker) { try { URL url = new URL("http://finance.yahoo.com/q?s=" + ticker + "&d=v1"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; StringBuffer page = new StringBuffer(8192); while ((line = reader.readLine()) != null) { page.append(line); } LispInterpreter lisp = InterpreterFactory.getInterpreter(); lisp.eval("(load \"nregex\")"); String quote = lisp.eval("(second (regex \"<b>([0-9][0-9]\\.[0-9][0-9])</b>\" \"" + cleanse(page) + "\"))"); System.out.println("Current quote: " + quote); lisp.exit(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception { Vector<SearchKeyResult> outVec = new Vector<SearchKeyResult>(); String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, "UTF-8"); URL url = new URL(uri); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); Pattern regex = Pattern.compile("pub.*?<a\\s+href\\s*=\"(.*?)\".*?>\\s*(\\w+)\\s*</a>.*?(\\d+-\\d+-\\d+).*?<a\\s+href\\s*=\".*?\".*?>\\s*(.+?)\\s*</a>", Pattern.CANON_EQ); String line; while ((line = input.readLine()) != null) { Matcher regexMatcher = regex.matcher(line); while (regexMatcher.find()) { String id = regexMatcher.group(2); String downUrl = iKeyServer + regexMatcher.group(1); String downDate = regexMatcher.group(3); String name = HTMLDecoder.decodeHTML(regexMatcher.group(4)); outVec.add(new SearchKeyResult(id, name, downDate, downUrl)); } } input.close(); return outVec; }
11
Code Sample 1: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; } Code Sample 2: public synchronized String decrypt(String plaintext) throws Exception { MessageDigest md = null; String strhash = new String((new BASE64Decoder()).decodeBuffer(plaintext)); System.out.println("strhash1122 " + strhash); try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } byte raw[] = md.digest(); try { md.update(new String(raw).getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } System.out.println("plain text " + strhash); String strcode = new String(raw); System.out.println("strcode.." + strcode); return strcode; }