label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: @Override public ImageData getImageData(URL url) { InputStream in = null; try { URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", "Tahiti/Alpha5x"); conn.setRequestProperty("agent-system", "aglets"); conn.setAllowUserInteraction(true); conn.connect(); in = conn.getInputStream(); String type = conn.getContentType(); int len = conn.getContentLength(); if (len < 0) { len = in.available(); } byte[] b = new byte[len]; int off = 0; int n = 0; while (n < len) { int count = in.read(b, off + n, len - n); if (count < 0) { throw new java.io.EOFException(); } n += count; } in.close(); return new AgletImageData(url, b, type); } catch (Exception ex) { ex.printStackTrace(); return null; } } Code Sample 2: String fetch_m3u(String m3u) { InputStream pstream = null; if (m3u.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; return line; } return null; }
11
Code Sample 1: private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } } Code Sample 2: public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
00
Code Sample 1: public String encode(String plain) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plain.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: public void testResponseTimeout() throws Exception { server.enqueue(new MockResponse().setBody("ABC").clearHeaders().addHeader("Content-Length: 4")); server.enqueue(new MockResponse().setBody("DEF")); server.play(); URLConnection urlConnection = server.getUrl("/").openConnection(); urlConnection.setReadTimeout(1000); InputStream in = urlConnection.getInputStream(); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); try { in.read(); fail(); } catch (SocketTimeoutException expected) { } URLConnection urlConnection2 = server.getUrl("/").openConnection(); InputStream in2 = urlConnection2.getInputStream(); assertEquals('D', in2.read()); assertEquals('E', in2.read()); assertEquals('F', in2.read()); assertEquals(-1, in2.read()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(0, server.takeRequest().getSequenceNumber()); }
11
Code Sample 1: public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.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!"); }
00
Code Sample 1: public GPSTrace loadGPSTrace(long reportID) { try { URL url = new URL(SERVER_URL + XML_PATH + "gps.xml"); System.out.println(url); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(url.openStream()); Element customerElement = document.getDocumentElement(); NodeList gps = customerElement.getElementsByTagName("gps"); trace = getGPSTrace(gps); } catch (SAXException sxe) { Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return trace; } Code Sample 2: private void copyResources(File oggDecDir, String[] resources, String resPrefix) throws FileNotFoundException, IOException { for (int i = 0; i < resources.length; i++) { String res = resPrefix + resources[i]; InputStream is = this.getClass().getResourceAsStream(res); if (is == null) throw new IllegalArgumentException("cannot find resource '" + res + "'"); File file = new File(oggDecDir, resources[i]); if (!file.exists() || file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copyStreams(is, fos); } finally { fos.close(); } } } }
00
Code Sample 1: public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; } Code Sample 2: public void putDataFiles(String server, String username, String password, String folder, String destinationFolder) { try { FTPClient ftp = new FTPClient(); ftp.connect(server); System.out.println("Connected"); ftp.login(username, password); System.out.println("Logged in to " + server + "."); System.out.print(ftp.getReplyString()); ftp.changeWorkingDirectory(destinationFolder); System.out.println("Changed to directory " + destinationFolder); File localRoot = new File(folder); File[] files = localRoot.listFiles(); System.out.println("Number of files in dir: " + files.length); for (int i = 0; i < files.length; i++) { putFiles(ftp, files[i]); } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } } Code Sample 2: private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); data = Data.valueOf(md.digest()); try { response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); setID(response.getWord()); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } }
00
Code Sample 1: @Override public DownloadingItem download(Playlist playlist, String title, File folder, StopDownloadCondition condition, String uuid) throws IOException, StoreStateException { boolean firstIteration = true; Iterator<PlaylistEntry> entries = playlist.getEntries().iterator(); DownloadingItem prevItem = null; File[] previousDownloadedFiles = new File[0]; while (entries.hasNext()) { PlaylistEntry entry = entries.next(); DownloadingItem item = null; LOGGER.info("Downloading from '" + entry.getTitle() + "'"); InputStream is = RESTHelper.inputStream(entry.getUrl()); boolean stopped = false; File nfile = null; try { nfile = createFileStream(folder, entry); item = new DownloadingItem(nfile, uuid.toString(), title, entry, new Date(), getPID(), condition); if (previousDownloadedFiles.length > 0) { item.setPreviousFiles(previousDownloadedFiles); } addItem(item); if (prevItem != null) deletePrevItem(prevItem); prevItem = item; stopped = IOUtils.copyStreams(is, new FileOutputStream(nfile), condition); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); radioScheduler.fireException(e); if (!condition.isStopped()) { File[] nfiles = new File[previousDownloadedFiles.length + 1]; System.arraycopy(previousDownloadedFiles, 0, nfiles, 0, previousDownloadedFiles.length); nfiles[nfiles.length - 1] = item.getFile(); previousDownloadedFiles = nfiles; if ((!entries.hasNext()) && (firstIteration)) { firstIteration = false; entries = playlist.getEntries().iterator(); } continue; } } if (stopped) { item.setState(ProcessStates.STOPPED); this.radioScheduler.fireStopDownloading(item); return item; } } return null; } Code Sample 2: private void insert(Connection c) throws SQLException { if (m_fromDb) throw new IllegalStateException("The record already exists in the database"); StringBuffer names = new StringBuffer("INSERT INTO ifServices (nodeID,ipAddr,serviceID"); StringBuffer values = new StringBuffer("?,?,?"); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) { values.append(",?"); names.append(",ifIndex"); } if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) { values.append(",?"); names.append(",status"); } if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { values.append(",?"); names.append(",lastGood"); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { values.append(",?"); names.append(",lastFail"); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) { values.append(",?"); names.append(",source"); } if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) { values.append(",?"); names.append(",notify"); } if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) { values.append(",?"); names.append(",qualifier"); } names.append(") VALUES (").append(values).append(')'); if (log().isDebugEnabled()) log().debug("DbIfServiceEntry.insert: SQL insert statment = " + names.toString()); PreparedStatement stmt = null; PreparedStatement delStmt = null; final DBUtils d = new DBUtils(getClass()); try { stmt = c.prepareStatement(names.toString()); d.watch(stmt); names = null; int ndx = 1; stmt.setInt(ndx++, m_nodeId); stmt.setString(ndx++, m_ipAddr.getHostAddress()); stmt.setInt(ndx++, m_serviceId); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) stmt.setInt(ndx++, m_ifIndex); if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) stmt.setString(ndx++, new String(new char[] { m_status })); if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { stmt.setTimestamp(ndx++, m_lastGood); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { stmt.setTimestamp(ndx++, m_lastFail); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) stmt.setString(ndx++, new String(new char[] { m_source })); if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) stmt.setString(ndx++, new String(new char[] { m_notify })); if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) stmt.setString(ndx++, m_qualifier); int rc; try { rc = stmt.executeUpdate(); } catch (SQLException e) { log().warn("ifServices DB insert got exception; will retry after " + "deletion of any existing records for this ifService " + "that are marked for deletion.", e); c.rollback(); String delCmd = "DELETE FROM ifServices WHERE status = 'D' " + "AND nodeid = ? AND ipAddr = ? AND serviceID = ?"; delStmt = c.prepareStatement(delCmd); d.watch(delStmt); delStmt.setInt(1, m_nodeId); delStmt.setString(2, m_ipAddr.getHostAddress()); delStmt.setInt(3, m_serviceId); rc = delStmt.executeUpdate(); rc = stmt.executeUpdate(); } log().debug("insert(): SQL update result = " + rc); } finally { d.cleanUp(); } m_fromDb = true; m_changed = 0; }
00
Code Sample 1: public void run() { FTPClient ftp = null; try { StarkHhDownloaderEtcProperties etcProperties = new StarkHhDownloaderEtcProperties(getUri()); StarkHhDownloaderVarProperties varProperties = new StarkHhDownloaderVarProperties(getUri()); ftp = new FTPClient(); int reply; ftp.connect(etcProperties.getHostname()); log("Connecting to ftp server at " + etcProperties.getHostname() + "."); log("Server replied with '" + ftp.getReplyString() + "'."); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw UserException.newOk("FTP server refused connection."); } log("Connected to server, now logging in."); ftp.login(etcProperties.getUsername(), etcProperties.getPassword()); log("Server replied with '" + ftp.getReplyString() + "'."); List<String> directories = etcProperties.getDirectories(); for (int i = 0; i < directories.size(); i++) { log("Checking the directory '" + directories.get(i) + "'."); boolean found = false; FTPFile[] filesArray = ftp.listFiles(directories.get(i)); List<FTPFile> files = Arrays.asList(filesArray); Collections.sort(files, new Comparator<FTPFile>() { public int compare(FTPFile file1, FTPFile file2) { if (file2.getTimestamp().getTime().equals(file1.getTimestamp().getTime())) { return file2.getName().compareTo(file1.getName()); } else { return file1.getTimestamp().getTime().compareTo(file2.getTimestamp().getTime()); } } }); for (FTPFile file : files) { if (file.getType() == FTPFile.FILE_TYPE && (varProperties.getLastImportDate(i) == null ? true : (file.getTimestamp().getTime().equals(varProperties.getLastImportDate(i).getDate()) ? file.getName().compareTo(varProperties.getLastImportName(i)) < 0 : file.getTimestamp().getTime().after(varProperties.getLastImportDate(i).getDate())))) { String fileName = directories.get(i) + "\\" + file.getName(); if (file.getSize() == 0) { log("Ignoring '" + fileName + "'because it has zero length"); } else { log("Attempting to download '" + fileName + "'."); InputStream is = ftp.retrieveFileStream(fileName); if (is == null) { reply = ftp.getReplyCode(); throw UserException.newOk("Can't download the file '" + file.getName() + "', server says: " + reply + "."); } log("File stream obtained successfully."); hhImporter = new HhDataImportProcess(getContract().getId(), new Long(0), is, fileName + ".df2", file.getSize()); hhImporter.run(); List<VFMessage> messages = hhImporter.getMessages(); hhImporter = null; if (messages.size() > 0) { for (VFMessage message : messages) { log(message.getDescription()); } throw UserException.newInvalidParameter("Problem loading file."); } } if (!ftp.completePendingCommand()) { throw UserException.newOk("Couldn't complete ftp transaction: " + ftp.getReplyString()); } varProperties.setLastImportDate(i, new MonadDate(file.getTimestamp().getTime())); varProperties.setLastImportName(i, file.getName()); found = true; } } if (!found) { log("No new files found."); } } } catch (UserException e) { try { log(e.getVFMessage().getDescription()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (IOException e) { try { log(e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (Throwable e) { try { log("Exception: " + e.getClass().getName() + " Message: " + e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } ChellowLogger.getLogger().logp(Level.SEVERE, "ContextListener", "contextInitialized", "Can't initialize context.", e); } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); log("Logged out."); } catch (IOException ioe) { } catch (ProgrammerException e) { } catch (UserException e) { } } } } Code Sample 2: public void xtest7() throws Exception { System.out.println("Lowagie"); FileInputStream inputStream = new FileInputStream("C:/Temp/arquivo.pdf"); PDFBoxManager manager = new PDFBoxManager(); InputStream[] images = manager.toImage(inputStream, "jpeg"); int count = 0; for (InputStream image : images) { FileOutputStream outputStream = new FileOutputStream("C:/Temp/arquivo_" + count + ".jpg"); IOUtils.copy(image, outputStream); count++; outputStream.close(); } inputStream.close(); }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/png"); OutputStream outStream; outStream = resp.getOutputStream(); InputStream is; String name = req.getParameter("name"); if (name == null) { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } else { ImageRecord imageRecord = imageBean.getFile(name); if (imageRecord != null) { is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile())); } else { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } } IOUtils.copy(is, outStream); outStream.close(); outStream.flush(); } Code Sample 2: private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static ContextInfo login(Context pContext, String pUsername, String pPwd, String pDeviceid) { HttpClient lClient = new DefaultHttpClient(); StringBuilder lBuilder = new StringBuilder(); ContextInfo lContextInfo = null; HttpPost lHttpPost = new HttpPost(new StringBuilder().append("http://").append(LoginActivity.mIpAddress.getText().toString()).append("/ZJWHServiceTest/GIS_Duty.asmx/PDALoginCheck").toString()); List<NameValuePair> lNameValuePairs = new ArrayList<NameValuePair>(2); lNameValuePairs.add(new BasicNameValuePair("username", pUsername)); lNameValuePairs.add(new BasicNameValuePair("password", pPwd)); lNameValuePairs.add(new BasicNameValuePair("deviceid", pDeviceid)); try { lHttpPost.setEntity(new UrlEncodedFormEntity(lNameValuePairs)); HttpResponse lResponse = lClient.execute(lHttpPost); BufferedReader lHeader = new BufferedReader(new InputStreamReader(lResponse.getEntity().getContent())); for (String s = lHeader.readLine(); s != null; s = lHeader.readLine()) { lBuilder.append(s); } String lResult = lBuilder.toString(); lResult = DataParseUtil.handleResponse(lResult); lContextInfo = LoginParseUtil.onlineParse(lResult); lContextInfo.setDeviceid(pDeviceid); if (0 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(0); } else if (1 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(1); updateUserInfo(pContext, lContextInfo); } else if (2 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(2); } else if (3 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(3); } } catch (Exception e) { return lContextInfo; } return lContextInfo; } Code Sample 2: @Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public static void readConfigFromResource(String resname) throws Exception { URL url = ConfigXMLReader.class.getClassLoader().getResource(resname); if (url == null) throw new FileNotFoundException("Couldn't find the config resource:" + resname); System.out.println("Reading config from resource: " + url.toString()); readConfig(url.openStream()); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static void copy(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: @Override protected RequestLogHandler createRequestLogHandler() { try { File logbackConf = File.createTempFile("logback-access", ".xml"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("logback-access.xml"), new FileOutputStream(logbackConf)); RequestLogHandler requestLogHandler = new RequestLogHandler(); RequestLogImpl requestLog = new RequestLogImpl(); requestLog.setFileName(logbackConf.getPath()); requestLogHandler.setRequestLog(requestLog); } catch (FileNotFoundException e) { log.error("Could not create request log handler", e); } catch (IOException e) { log.error("Could not create request log handler", e); } return null; } Code Sample 2: private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public static SearchItem loadRecord(String id, boolean isContact) { String line = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(isContact ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", Common.token)); nameValuePairs.add(new BasicNameValuePair("id", id)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, isContact ? "Name__Last__First_" : "Name"); String phone = ""; if (!isContact) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, isContact ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, isContact ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); SearchItem item = new SearchItem(); item.set(1, Name__Last__First_); item.set(2, phone); item.set(3, phone); item.set(4, Email1); item.set(5, Home_Fax); item.set(6, Address1); item.set(7, Address2); item.set(8, City); item.set(9, State); item.set(10, Zip); item.set(11, Profile); item.set(12, Country); item.set(13, success); item.set(14, error); return item; } catch (Exception e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; line = null; } return null; } Code Sample 2: private void parseXmlFile() throws IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); if (file != null) { dom = db.parse(file); } else { dom = db.parse(url.openStream()); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
11
Code Sample 1: private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); } Code Sample 2: static void linkBlocks(File from, File to, int oldLV) throws IOException { if (!from.isDirectory()) { if (from.getName().startsWith(COPY_FILE_PREFIX)) { IOUtils.copyBytes(new FileInputStream(from), new FileOutputStream(to), 16 * 1024, true); } else { if (oldLV >= PRE_GENERATIONSTAMP_LAYOUT_VERSION) { to = new File(convertMetatadataFileName(to.getAbsolutePath())); } HardLink.createHardLink(from, to); } return; } if (!to.mkdir()) throw new IOException("Cannot create directory " + to); String[] blockNames = from.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(BLOCK_FILE_PREFIX) || name.startsWith(COPY_FILE_PREFIX); } }); for (int i = 0; i < blockNames.length; i++) linkBlocks(new File(from, blockNames[i]), new File(to, blockNames[i]), oldLV); }
11
Code Sample 1: public void modify(String strName, String strNewPass) { String str = "update jb_user set V_PASSWORD =? where V_USERNAME =?"; Connection con = null; PreparedStatement pstmt = null; try { con = DbForumFactory.getConnection(); con.setAutoCommit(false); pstmt = con.prepareStatement(str); pstmt.setString(1, SecurityUtil.md5ByHex(strNewPass)); pstmt.setString(2, strName); pstmt.executeUpdate(); con.commit(); } catch (Exception e) { e.printStackTrace(); try { con.rollback(); } catch (SQLException e1) { } } finally { try { DbForumFactory.closeDB(null, pstmt, null, con); } catch (Exception e) { } } } Code Sample 2: public Long processAddCompany(Company companyBean, String userLogin, Long holdingId, AuthSession authSession) { if (authSession == null) { return null; } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_LIST_COMPANY"); seq.setTableName("WM_LIST_COMPANY"); seq.setColumnName("ID_FIRM"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_LIST_COMPANY (" + " ID_FIRM, " + " full_name, " + " short_name, " + " address, " + " telefon_buh, " + " telefon_chief, " + " chief, " + " buh, " + " fax, " + " email, " + " icq, " + " short_client_info, " + " url, " + " short_info, " + "is_deleted" + ")" + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " select " + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?,0 from WM_AUTH_USER " + "where USER_LOGIN=? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, sequenceValue); ps.setString(num++, companyBean.getName()); ps.setString(num++, companyBean.getShortName()); ps.setString(num++, companyBean.getAddress()); ps.setString(num++, ""); ps.setString(num++, ""); ps.setString(num++, companyBean.getCeo()); ps.setString(num++, companyBean.getCfo()); ps.setString(num++, ""); ps.setString(num++, ""); RsetTools.setLong(ps, num++, null); ps.setString(num++, ""); ps.setString(num++, companyBean.getWebsite()); ps.setString(num++, companyBean.getInfo()); ps.setString(num++, userLogin); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); if (holdingId != null) { InternalDaoFactory.getInternalHoldingDao().setRelateHoldingCompany(dbDyn, holdingId, sequenceValue); } dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
00
Code Sample 1: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } Code Sample 2: static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } }
00
Code Sample 1: public static String calcHA1(String algorithm, String username, String realm, String password, String nonce, String cnonce) throws FatalException, MD5DigestException { MD5Encoder encoder = new MD5Encoder(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new FatalException(e); } if (username == null || realm == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "username or realm"); } if (password == null) { System.err.println("No password has been provided"); throw new IllegalStateException(); } if (algorithm != null && algorithm.equals("MD5-sess") && (nonce == null || cnonce == null)) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce or cnonce"); } md5.update((username + ":" + realm + ":" + password).getBytes()); if (algorithm != null && algorithm.equals("MD5-sess")) { md5.update((":" + nonce + ":" + cnonce).getBytes()); } return encoder.encode(md5.digest()); } Code Sample 2: private static InputStream connect(String url) throws IOException { int status = 0; String currentlyActiveServer = getCurrentlyActiveServer(); try { long begin = System.currentTimeMillis(); HttpURLConnection httpConnection = (HttpURLConnection) new URL(currentlyActiveServer + url).openConnection(); httpConnection.setConnectTimeout(connectTimeOut); httpConnection.setReadTimeout(readTimeOut); httpConnection.setRequestProperty("User-Agent", USER_AGENT); InputStream in = httpConnection.getInputStream(); status = httpConnection.getResponseCode(); if (status == 200) { long elapsedTime = System.currentTimeMillis() - begin; averageConnectTime = (averageConnectTime * (averageSampleSize - 1) + elapsedTime) / averageSampleSize; if (geoNamesServerFailover != null && averageConnectTime > 5000 && !currentlyActiveServer.equals(geoNamesServerFailover)) { timeOfLastFailureMainServer = System.currentTimeMillis(); } return in; } } catch (IOException e) { return tryFailoverServer(url, currentlyActiveServer, 0, e); } IOException ioException = new IOException("status code " + status + " for " + url); return tryFailoverServer(url, currentlyActiveServer, status, ioException); }
00
Code Sample 1: public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: java SOAPClient4XG " + "http://soapURL soapEnvelopefile.xml" + " [SOAPAction]"); System.err.println("SOAPAction is optional."); System.exit(1); } String SOAPUrl = args[0]; String xmlFile2Send = args[1]; String SOAPAction = ""; if (args.length > 2) SOAPAction = args[2]; URL url = new URL(SOAPUrl); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } Code Sample 2: public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } }
00
Code Sample 1: 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); } } Code Sample 2: private void addLine(AmazonItem coverAdress) { try { URL url = new URL("" + coverAdress.getMediumImageURL()); TableItem ligne1 = new TableItem(table, SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_MNEMONIC); url.openConnection(); InputStream is = url.openStream(); Image coverPicture = new Image(display, is); coverAvailable.add(url); ligne1.setImage(new Image[] { coverPicture, null }); ligne1.setText(new String[] { null, coverAdress.getArtist() + "\n" + coverAdress.getCDTitle() + "\nTrack : " + coverAdress.getNbTrack() }); } catch (MalformedURLException e) { } catch (IOException e) { System.err.println(e.toString()); } }
11
Code Sample 1: public static void joinFiles(FileValidator validator, File target, File[] sources) { FileOutputStream fos = null; try { if (!validator.verifyFile(target)) return; fos = new FileOutputStream(target); FileInputStream fis = null; byte[] bytes = new byte[512]; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); int nbread = 0; try { while ((nbread = fis.read(bytes)) > -1) { fos.write(bytes, 0, nbread); } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { fis.close(); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } Code Sample 2: public void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } }
00
Code Sample 1: private void DrawModel(Graphics offg, int obj_num, boolean object, float h, float s, int vt_num, int fc_num) { int px[] = new int[3]; int py[] = new int[3]; int count = 0; int tmp[] = new int[fc_num]; double tmp_depth[] = new double[fc_num]; rotate(vt_num); offg.setColor(Color.black); for (int i = 0; i < fc_num; i++) { double a1 = fc[i].vt1.x - fc[i].vt0.x; double a2 = fc[i].vt1.y - fc[i].vt0.y; double a3 = fc[i].vt1.z - fc[i].vt0.z; double b1 = fc[i].vt2.x - fc[i].vt1.x; double b2 = fc[i].vt2.y - fc[i].vt1.y; double b3 = fc[i].vt2.z - fc[i].vt1.z; fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; fc[i].nz = a1 * b2 - a2 * b1; if (fc[i].nz < 0) { fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; tmp[count] = i; tmp_depth[count] = fc[i].getDepth(); count++; } } int lim = count - 1; do { int m = 0; for (int n = 0; n <= lim - 1; n++) { if (tmp_depth[n] < tmp_depth[n + 1]) { double t = tmp_depth[n]; tmp_depth[n] = tmp_depth[n + 1]; tmp_depth[n + 1] = t; int ti = tmp[n]; tmp[n] = tmp[n + 1]; tmp[n + 1] = ti; m = n; } } lim = m; } while (lim != 0); for (int m = 0; m < count; m++) { int i = tmp[m]; double l = Math.sqrt(fc[i].nx * fc[i].nx + fc[i].ny * fc[i].ny + fc[i].nz * fc[i].nz); test(offg, i, l, h, s); px[0] = (int) (fc[i].vt0.x * m_Scale + centerp.x); py[0] = (int) (-fc[i].vt0.y * m_Scale + centerp.y); px[1] = (int) (fc[i].vt1.x * m_Scale + centerp.x); py[1] = (int) (-fc[i].vt1.y * m_Scale + centerp.y); px[2] = (int) (fc[i].vt2.x * m_Scale + centerp.x); py[2] = (int) (-fc[i].vt2.y * m_Scale + centerp.y); offg.fillPolygon(px, py, 3); } if (labelFlag && object) { offg.setFont(Fonts.FONT_REAL); offg.drawString(d_con.getPointerData().getRealObjName(obj_num), (int) ((fc[0].vt0.x + 10) * m_Scale + centerp.x), (int) (-(fc[0].vt0.y + 10) * m_Scale + centerp.y)); } } Code Sample 2: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); }
00
Code Sample 1: public static int doPost(String urlString, String username, String password, Map<String, String> parameters) throws IOException { PrintWriter out = null; try { URL url = new URL(urlString); URLConnection connection = url.openConnection(); if (username != null && password != null) { String encoding = base64Encode(username + ':' + password); connection.setRequestProperty("Authorization", "Basic " + encoding); } connection.setDoOutput(true); out = new PrintWriter(connection.getOutputStream()); boolean first = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (first) { first = false; } else { out.print('&'); } out.print(entry.getKey()); out.print('='); out.print(URLEncoder.encode(entry.getValue(), "UTF-8")); } out.close(); connection.connect(); if (!(connection instanceof HttpURLConnection)) { throw new IOException(); } return ((HttpURLConnection) connection).getResponseCode(); } catch (IOException ex) { throw ex; } finally { if (out != null) { out.close(); } } } Code Sample 2: public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } }
11
Code Sample 1: public void uploadFile(String filename) throws RQLException { checkFtpClient(); OutputStream out = null; try { out = ftpClient.storeFileStream(filename); IOUtils.copy(new FileReader(filename), out); out.close(); ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Upload of local file with name " + filename + " via FTP to server " + server + " failed.", ex); } } Code Sample 2: private void initialize() { if (!initialized) { if (context.getJavadocLinks() != null) { for (String url : context.getJavadocLinks()) { if (!url.endsWith("/")) { url += "/"; } StringWriter writer = new StringWriter(); try { IOUtils.copy(new URL(url + "package-list").openStream(), writer); } catch (Exception e) { e.printStackTrace(); continue; } StringTokenizer tokenizer2 = new StringTokenizer(writer.toString()); while (tokenizer2.hasMoreTokens()) { javadocByPackage.put(tokenizer2.nextToken(), url); } } } initialized = true; } }
11
Code Sample 1: public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements(); ) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeDraftMessage(getId(), mime, user); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } } Code Sample 2: public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } }
11
Code Sample 1: protected long incrementInDatabase(Object type) { long current_value; long new_value; String entry; if (global_entry != null) entry = global_entry; else throw new UnsupportedOperationException("Named key generators are not yet supported."); String lkw = (String) properties.get("net.ontopia.topicmaps.impl.rdbms.HighLowKeyGenerator.SelectSuffix"); String sql_select; if (lkw == null && (database.equals("sqlserver"))) { sql_select = "select " + valcol + " from " + table + " with (XLOCK) where " + keycol + " = ?"; } else { if (lkw == null) { if (database.equals("sapdb")) lkw = "with lock"; else lkw = "for update"; } sql_select = "select " + valcol + " from " + table + " where " + keycol + " = ? " + lkw; } if (log.isDebugEnabled()) log.debug("KeyGenerator: retrieving: " + sql_select); Connection conn = null; try { conn = connfactory.requestConnection(); PreparedStatement stm1 = conn.prepareStatement(sql_select); try { stm1.setString(1, entry); ResultSet rs = stm1.executeQuery(); if (!rs.next()) throw new OntopiaRuntimeException("HIGH/LOW key generator table '" + table + "' not initialized (no rows)."); current_value = rs.getLong(1); rs.close(); } finally { stm1.close(); } new_value = current_value + grabsize; String sql_update = "update " + table + " set " + valcol + " = ? where " + keycol + " = ?"; if (log.isDebugEnabled()) log.debug("KeyGenerator: incrementing: " + sql_update); PreparedStatement stm2 = conn.prepareStatement(sql_update); try { stm2.setLong(1, new_value); stm2.setString(2, entry); stm2.executeUpdate(); } finally { stm2.close(); } conn.commit(); } catch (SQLException e) { try { if (conn != null) conn.rollback(); } catch (SQLException e2) { } throw new OntopiaRuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { throw new OntopiaRuntimeException(e); } } } value = current_value + 1; max_value = new_value; return value; } Code Sample 2: public void testSavepoint4() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #savepoint4 (data int)"); stmt.close(); con.setAutoCommit(false); for (int i = 0; i < 3; i++) { PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)"); pstmt.setInt(1, 1); assertTrue(pstmt.executeUpdate() == 1); Savepoint savepoint = con.setSavepoint(); assertNotNull(savepoint); assertTrue(savepoint.getSavepointId() == 1); try { savepoint.getSavepointName(); assertTrue(false); } catch (SQLException e) { } pstmt.setInt(1, 2); assertTrue(pstmt.executeUpdate() == 1); pstmt.close(); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(savepoint); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(); } con.setAutoCommit(true); }
11
Code Sample 1: private HashSet<String> href(String urlstr) throws IOException { HashSet<String> hrefs = new HashSet<String>(); URL url = new URL(urlstr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", "_session_id=" + _session_id); InputStreamReader r = new InputStreamReader(con.getInputStream()); StringWriter b = new StringWriter(); IOUtils.copyTo(r, b); r.close(); try { Thread.sleep(WAIT_SECONDS * 1000); } catch (Exception err) { } String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]"); for (String s1 : tokens) { if (!(s1.startsWith("a") && s1.contains("href"))) continue; String tokens2[] = s1.split("[\\\"\\\']"); for (String s2 : tokens2) { if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue; hrefs.add(s2); } } return hrefs; } Code Sample 2: public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream contentIn2 = getClass().getResourceAsStream(CONTENT2_FILE); sourceOut = emptySource.getOutputStream(); try { IOUtils.copy(contentIn2, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn2.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT2_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
11
Code Sample 1: private void doConvert(HttpServletResponse response, ConversionRequestResolver rr, EGE ege, ConversionsPath cpath) throws FileUploadException, IOException, RequestResolvingException, EGEException, FileNotFoundException, ConverterException, ZipException { InputStream is = null; OutputStream os = null; if (ServletFileUpload.isMultipartContent(rr.getRequest())) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(rr.getRequest()); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { is = item.openStream(); applyConversionsProperties(rr.getConversionProperties(), cpath); DataBuffer buffer = new DataBuffer(0, EGEConstants.BUFFER_TEMP_PATH); String alloc = buffer.allocate(is); InputStream ins = buffer.getDataAsStream(alloc); is.close(); try { ValidationResult vRes = ege.performValidation(ins, cpath.getInputDataType()); if (vRes.getStatus().equals(ValidationResult.Status.FATAL)) { ValidationServlet valServ = new ValidationServlet(); valServ.printValidationResult(response, vRes); try { ins.close(); } finally { buffer.removeData(alloc, true); } return; } } catch (ValidatorException vex) { LOGGER.warn(vex.getMessage()); } finally { try { ins.close(); } catch (Exception ex) { } } File zipFile = null; FileOutputStream fos = null; String newTemp = UUID.randomUUID().toString(); IOResolver ior = EGEConfigurationManager.getInstance().getStandardIOResolver(); File buffDir = new File(buffer.getDataDir(alloc)); zipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + EZP_EXT); fos = new FileOutputStream(zipFile); ior.compressData(buffDir, fos); ins = new FileInputStream(zipFile); File szipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + ZIP_EXT); fos = new FileOutputStream(szipFile); try { try { ege.performConversion(ins, fos, cpath); } finally { fos.close(); } boolean isComplex = EGEIOUtils.isComplexZip(szipFile); response.setContentType(APPLICATION_OCTET_STREAM); String fN = item.getName().substring(0, item.getName().lastIndexOf(".")); if (isComplex) { String fileExt; if (cpath.getOutputDataType().getMimeType().equals(APPLICATION_MSWORD)) { fileExt = DOCX_EXT; } else { fileExt = ZIP_EXT; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); FileInputStream fis = new FileInputStream(szipFile); os = response.getOutputStream(); try { EGEIOUtils.copyStream(fis, os); } finally { fis.close(); } } else { String fileExt = getMimeExtensionProvider().getFileExtension(cpath.getOutputDataType().getMimeType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); os = response.getOutputStream(); EGEIOUtils.unzipSingleFile(new ZipFile(szipFile), os); } } finally { ins.close(); if (os != null) { os.flush(); os.close(); } buffer.clear(true); szipFile.delete(); if (zipFile != null) { zipFile.delete(); } } } } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } } Code Sample 2: private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: destination file is unwriteable: " + toFileName); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: private static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public String md5Encode(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(pass.getBytes()); byte[] result = md.digest(); return new String(result); }
11
Code Sample 1: public static boolean copy(InputStream is, File file) { try { IOUtils.copy(is, new FileOutputStream(file)); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: 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(); } }
11
Code Sample 1: public static void copy(File in, File out) throws IOException { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } Code Sample 2: public static void main(String[] args) { String WTKdir = null; String sourceFile = null; String instrFile = null; String outFile = null; String jadFile = null; Manifest mnf; if (args.length == 0) { usage(); return; } int i = 0; while (i < args.length && args[i].startsWith("-")) { if (("-WTK".equals(args[i])) && (i < args.length - 1)) { i++; WTKdir = args[i]; } else if (("-source".equals(args[i])) && (i < args.length - 1)) { i++; sourceFile = args[i]; } else if (("-instr".equals(args[i])) && (i < args.length - 1)) { i++; instrFile = args[i]; } else if (("-o".equals(args[i])) && (i < args.length - 1)) { i++; outFile = args[i]; } else if (("-jad".equals(args[i])) && (i < args.length - 1)) { i++; jadFile = args[i]; } else { System.out.println("Error: Unrecognized option: " + args[i]); System.exit(0); } i++; } if (WTKdir == null || sourceFile == null || instrFile == null) { System.out.println("Error: Missing parameter!!!"); usage(); return; } if (outFile == null) outFile = sourceFile; FileInputStream fisJar; try { fisJar = new FileInputStream(sourceFile); } catch (FileNotFoundException e1) { System.out.println("Cannot find source jar file: " + sourceFile); e1.printStackTrace(); return; } FileOutputStream fosJar; File aux = null; try { aux = File.createTempFile("predef", "aux"); fosJar = new FileOutputStream(aux); } catch (IOException e1) { System.out.println("Cannot find temporary jar file: " + aux); e1.printStackTrace(); return; } JarFile instrJar = null; Enumeration en = null; File tempDir = null; try { instrJar = new JarFile(instrFile); en = instrJar.entries(); tempDir = File.createTempFile("jbtp", ""); tempDir.delete(); System.out.println("Create directory: " + tempDir.mkdirs()); tempDir.deleteOnExit(); } catch (IOException e) { System.out.println("Cannot open instrumented file: " + instrFile); e.printStackTrace(); return; } String[] wtklib = new java.io.File(WTKdir + File.separator + "lib").list(new OnlyJar()); String preverifyCmd = WTKdir + File.separator + "bin" + File.separator + "preverify -classpath " + WTKdir + File.separator + "lib" + File.separator + CLDC_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + MIDP_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + WMA_JAR + File.pathSeparator + instrFile; for (int k = 0; k < wtklib.length; k++) { preverifyCmd += File.pathSeparator + WTKdir + File.separator + "lib" + wtklib[k]; } preverifyCmd += " " + "-d " + tempDir.getAbsolutePath() + " "; while (en.hasMoreElements()) { JarEntry je = (JarEntry) en.nextElement(); String jeName = je.getName(); if (jeName.endsWith(".class")) jeName = jeName.substring(0, jeName.length() - 6); preverifyCmd += jeName + " "; } try { Process p = Runtime.getRuntime().exec(preverifyCmd); if (p.waitFor() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Error calling the preverify command."); while (in.ready()) { System.out.print("" + in.readLine()); } System.out.println(); in.close(); return; } } catch (Exception e) { System.out.println("Cannot execute preverify command"); e.printStackTrace(); return; } File[] listOfFiles = computeFiles(tempDir); System.out.println("-------------------------------\n" + "Files to insert: "); String[] strFiles = new String[listOfFiles.length]; int l = tempDir.toString().length() + 1; for (int j = 0; j < listOfFiles.length; j++) { strFiles[j] = listOfFiles[j].toString().substring(l); strFiles[j] = strFiles[j].replace(File.separatorChar, '/'); System.out.println(strFiles[j]); } System.out.println("-------------------------------"); try { JarInputStream jis = new JarInputStream(fisJar); mnf = jis.getManifest(); JarOutputStream jos = new JarOutputStream(fosJar, mnf); nextJar: for (JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry()) { String s = je.getName(); for (int k = 0; k < strFiles.length; k++) { if (strFiles[k].equals(s)) continue nextJar; } jos.putNextEntry(je); byte[] b = new byte[512]; for (int k = jis.read(b, 0, 512); k >= 0; k = jis.read(b, 0, 512)) { jos.write(b, 0, k); } } jis.close(); for (int j = 0; j < strFiles.length; j++) { FileInputStream fis = new FileInputStream(listOfFiles[j]); JarEntry je = new JarEntry(strFiles[j]); jos.putNextEntry(je); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); jos.write(b, 0, k); } fis.close(); } jos.close(); fisJar.close(); fosJar.close(); } catch (IOException e) { System.out.println("Cannot read/write jar file."); e.printStackTrace(); return; } try { FileOutputStream fos = new FileOutputStream(outFile); FileInputStream fis = new FileInputStream(aux); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); fos.write(b, 0, k); } fis.close(); fos.close(); } catch (IOException e) { System.out.println("Cannot write output jar file: " + outFile); e.printStackTrace(); } Iterator it; Attributes atr; atr = mnf.getMainAttributes(); it = atr.keySet().iterator(); if (jadFile != null) { FileOutputStream fos; try { File outJarFile = new File(outFile); fos = new FileOutputStream(jadFile); PrintStream psjad = new PrintStream(fos); while (it.hasNext()) { Object ats = it.next(); psjad.println(ats + ": " + atr.get(ats)); } psjad.println("MIDlet-Jar-URL: " + outFile); psjad.println("MIDlet-Jar-Size: " + outJarFile.length()); fos.close(); } catch (IOException eio) { System.out.println("Cannot create jad file."); eio.printStackTrace(); } } }
00
Code Sample 1: public Constructor run() throws Exception { String path = "META-INF/services/" + ComponentApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = ComponentApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (ComponentApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new ComponentApplicationException("No " + "ComponentApplicationContext implementation " + "found."); } Code Sample 2: public static void copyFile(File in, File out, long maxCount) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); if (maxCount == 0) maxCount = sourceChannel.size(); try { final long size = sourceChannel.size(); long position = 0; while (position < size) { position += sourceChannel.transferTo(position, maxCount, destinationChannel); } } finally { sourceChannel.close(); destinationChannel.close(); } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } 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(); } } }
00
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 { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } 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: @Override public synchronized void deleteCallStatistics(Integer elementId, String contextName, String category, String project, String name, Date dateFrom, Date dateTo, Boolean extractException, String principal) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getCallInvocationsSchemaAndTableName() + " FROM " + this.getCallInvocationsSchemaAndTableName() + " INNER JOIN " + this.getCallElementsSchemaAndTableName() + " ON " + this.getCallElementsSchemaAndTableName() + ".element_id = " + this.getCallInvocationsSchemaAndTableName() + ".element_id "; if (principal != null) { queryString = queryString + "LEFT JOIN " + this.getCallPrincipalsSchemaAndTableName() + " ON " + this.getCallInvocationsSchemaAndTableName() + ".principal_id = " + this.getCallPrincipalsSchemaAndTableName() + ".principal_id "; } queryString = queryString + "WHERE "; if (elementId != null) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".elementId = ? AND "; } if (contextName != null) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".context_name LIKE ? AND "; } if ((category != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".category LIKE ? AND "; } if ((project != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".project LIKE ? AND "; } if ((name != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".name LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".start_timestamp <= ? AND "; } if (principal != null) { queryString = queryString + this.getCallPrincipalsSchemaAndTableName() + ".principal_name LIKE ? AND "; } if (extractException != null) { if (extractException.booleanValue()) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NOT NULL AND "; } else { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NULL AND "; } } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (elementId != null) { preparedStatement.setLong(indexCounter, elementId.longValue()); indexCounter = indexCounter + 1; } if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if ((category != null)) { preparedStatement.setString(indexCounter, category); indexCounter = indexCounter + 1; } if ((project != null)) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if ((name != null)) { preparedStatement.setString(indexCounter, name); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } if (principal != null) { preparedStatement.setString(indexCounter, principal); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting call statistics.", e); } finally { this.releaseConnection(connection); } }
00
Code Sample 1: public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException { URI uri = request.getURI(); String original = uri.toString(); UrlRules rules = UrlRules.getRules(mResolver); UrlRules.Rule rule = rules.matchRule(original); String rewritten = rule.apply(original); if (rewritten == null) { Log.w(TAG, "Blocked by " + rule.mName + ": " + original); throw new BlockedRequestException(rule); } else if (rewritten == original) { return executeWithoutRewriting(request, context); } try { uri = new URI(rewritten); } catch (URISyntaxException e) { throw new RuntimeException("Bad URL from rule: " + rule.mName, e); } RequestWrapper wrapper = wrapRequest(request); wrapper.setURI(uri); request = wrapper; if (LOCAL_LOGV) Log.v(TAG, "Rule " + rule.mName + ": " + original + " -> " + rewritten); return executeWithoutRewriting(request, context); } Code Sample 2: private static InputStream openStream(final URL url) throws IOException { try { return (InputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return url.openStream(); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
11
Code Sample 1: private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException, XMLStreamException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); byte[] byteArray = baos.toByteArray(); String resMessage = new String(byteArray, "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + resMessage); return resMessage; }
00
Code Sample 1: private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; } Code Sample 2: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
11
Code Sample 1: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } Code Sample 2: public TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
00
Code Sample 1: public StringBuffer get(URL url) throws IOException { StringBuffer pageContents = new StringBuffer(); PDFReader reader = new PDFReader(url.openStream()); reader.open(); int pageCount = reader.getNumberOfPages(); for (int i = 0; i < pageCount; i++) pageContents.append(new String(reader.extractTextFromPage(i).getBytes(), "UTF-8")); reader.close(); return pageContents; } Code Sample 2: public final int connectAndLogin(Uri u, boolean cwd) throws UnknownHostException, IOException, InterruptedException { if (ftp.isLoggedIn()) { if (cwd) { String path = u.getPath(); if (path != null) ftp.setCurrentDir(path); } return WAS_IN; } int port = u.getPort(); if (port == -1) port = 21; String host = u.getHost(); if (ftp.connect(host, port)) { if (theUserPass == null || theUserPass.isNotSet()) theUserPass = new FTPCredentials(u.getUserInfo()); if (ftp.login(theUserPass.getUserName(), theUserPass.getPassword())) { if (cwd) { String path = u.getPath(); if (path != null) ftp.setCurrentDir(path); } return LOGGED_IN; } else { ftp.logout(true); ftp.disconnect(); Log.w(TAG, "Invalid credentials."); return NO_LOGIN; } } return NO_CONNECT; }
11
Code Sample 1: void writeToFile(String dir, InputStream input, String fileName) throws FileNotFoundException, IOException { makeDirs(dir); FileOutputStream fo = null; try { System.out.println(Thread.currentThread().getName() + " : " + "Writing file " + fileName + " to path " + dir); File file = new File(dir, fileName); fo = new FileOutputStream(file); IOUtils.copy(input, fo); } catch (Exception e) { e.printStackTrace(); System.err.println("Failed to write " + fileName); } } Code Sample 2: public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } }
00
Code Sample 1: public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: public List<SuspectFileProcessingStatus> retrieve() throws Exception { BufferedOutputStream bos = null; try { String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/"); listFilePath = listFilePath.concat(".xml"); if (!new File(getDownloadDirectoryPath()).exists()) { FileUtils.forceMkdir(new File(getDownloadDirectoryPath())); } FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath); bos = new BufferedOutputStream(listFileOutputStream); InputStream is = null; if (getUseProxy()) { is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort()); IOUtils.copyLarge(is, bos); } else { URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null); } bos.flush(); bos.close(); File listFile = new File(listFilePath); if (!listFile.exists()) { throw new IllegalStateException("The list file did not get created"); } if (isLoggingInfo()) { logInfo("Downloaded list file : " + listFile); } List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>(); String loadType = GeneralConstants.LOAD_TYPE_FULL; String feedType = GeneralConstants.EMPTY_TOKEN; String listName = getListName(); String errorCode = ""; String description = ""; SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description); sfpsList.add(sfps); if (isLoggingInfo()) { logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps); } return sfpsList; } finally { if (null != bos) { bos.close(); } } }
00
Code Sample 1: @Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File(srcRootPath + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try { srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File(destRootPath + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("Exception", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } } return res; } Code Sample 2: 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(); }
00
Code Sample 1: private String determineGuardedHtml() { StringBuffer buf = new StringBuffer(); if (m_guardedButtonPresent) { buf.append("\n<span id='" + getHtmlIdPrefix() + PUSH_PAGE_SUFFIX + "' style='display:none'>\n"); String location = m_guardedHtmlLocation != null ? m_guardedHtmlLocation : (String) Config.getProperty(Config.PROP_PRESENTATION_DEFAULT_GUARDED_HTML_LOCATION); String html = (String) c_guardedHtmlCache.get(location); if (html == null) { if (log.isDebugEnabled()) log.debug(this.NAME + ".determineGuardedHtml: Reading the Guarded Html Fragment: " + location); URL url = getUrl(location); if (url != null) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf1 = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf1.append(line); buf1.append('\n'); } html = buf1.toString(); } catch (IOException e) { log.warn(this.NAME + ".determineGuardedHtml: Failed to read the Guarded Html Fragment: " + location, e); } finally { try { if (in != null) in.close(); } catch (IOException ex) { log.warn(this.NAME + ".determineGuardedHtml: Failed to close the Guarded Html Fragment: " + location, ex); } } } else { log.warn("Failed to read the Guarded Html Fragment: " + location); } if (html == null) html = "Transaction in Progress"; c_guardedHtmlCache.put(location, html); } buf.append(html); buf.append("\n</span>\n"); } return buf.toString(); } Code Sample 2: public static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString) throws IOException { dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false); if (!srcFS.getFileStatus(srcDir).isDir()) return false; OutputStream out = dstFS.create(dstFile); try { FileStatus contents[] = srcFS.listStatus(srcDir); for (int i = 0; i < contents.length; i++) { if (!contents[i].isDir()) { InputStream in = srcFS.open(contents[i].getPath()); try { IOUtils.copyBytes(in, out, conf, false); if (addString != null) out.write(addString.getBytes("UTF-8")); } finally { in.close(); } } } } finally { out.close(); } if (deleteSource) { return srcFS.delete(srcDir, true); } else { return true; } }
00
Code Sample 1: public void init() { String inputLine = ""; String registeredLine = ""; println("Insert RSS link:"); String urlString = sc.nextLine(); if (urlString.length() == 0) init(); println("Working..."); BufferedReader in = null; URL url = null; try { url = new URL(urlString); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) registeredLine += inputLine; in.close(); } catch (MalformedURLException e2) { e2.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } File elenco = new File("elenco.txt"); PrintWriter pout = null; try { pout = new PrintWriter(elenco); } catch (FileNotFoundException e1) { e1.printStackTrace(); } Vector<String> vector = new Vector<String>(); int endIndex = 0; int numeroFoto = 0; while ((registeredLine = registeredLine.substring(endIndex)).length() > 10) { int startIndex = registeredLine.indexOf("<media:content url='"); if (startIndex == -1) break; registeredLine = registeredLine.substring(startIndex); String address = ""; startIndex = registeredLine.indexOf("http://"); endIndex = registeredLine.indexOf("' height"); address = registeredLine.substring(startIndex, endIndex); println(address); pout.println(address); vector.add(address); numeroFoto++; } if (pout.checkError()) println("ERROR"); println("Images number: " + numeroFoto); if (numeroFoto == 0) { println("No photos found, WebAlbum is empty or the RSS link is incorrect."); sc.nextLine(); System.exit(0); } println("Start downloading? (y/n)"); if (!sc.nextLine().equalsIgnoreCase("y")) System.exit(0); SimpleDateFormat data = new SimpleDateFormat("dd-MM-yy_HH.mm"); Calendar oggi = Calendar.getInstance(); String cartella = data.format(oggi.getTime()); boolean success = new File(cartella).mkdir(); if (success) println("Sub-directory created..."); println("downloading...\npress ctrl-C to stop"); BufferedInputStream bin = null; BufferedOutputStream bout = null; URL photoAddr = null; int len = 0; for (int x = 0; x < vector.size(); x++) { println("file " + (x + 1) + " of " + numeroFoto); try { photoAddr = new URL(vector.get(x)); bin = new BufferedInputStream(photoAddr.openStream()); bout = new BufferedOutputStream(new FileOutputStream(cartella + "/" + (x + 1) + ".jpg")); while ((len = bin.read()) != -1) bout.write(len); bout.flush(); bout.close(); bin.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } println("Done!"); } Code Sample 2: private static String format(String check) throws NoSuchAlgorithmException, UnsupportedEncodingException { check = check.replaceAll(" ", ""); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(check.getBytes("ISO-8859-1")); byte[] end = md5.digest(); String digest = ""; for (int i = 0; i < end.length; i++) { digest += ((end[i] & 0xff) < 16 ? "0" : "") + Integer.toHexString(end[i] & 0xff); } return digest; }
11
Code Sample 1: private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } } Code Sample 2: public void test() throws Exception { TranslationResponseStorage r = new TranslationResponseStorage(mockStorage, "UTF-8"); MockResponseStateObserver observer = new MockResponseStateObserver(); r.addStateObserver(observer); assertEquals("UTF-8", r.getCharacterEncoding()); assertEquals(-1L, r.getLastModified()); assertEquals(0, r.getTranslationCount()); r.setTranslationCount(10); assertEquals(10, r.getTranslationCount()); assertNotNull(r.getHeadersStorage()); assertNull(r.getHeaders()); r.setLastModified(100000L); assertEquals(100000L, r.getLastModified()); assertFalse(r.getHeaders().isEmpty()); { Set<ResponseHeader> set = new TreeSet<ResponseHeader>(); set.add(new ResponseHeaderImpl("Last-Modified", new String[] { DateUtil.formatDate(new Date(200000L)) })); r.addHeaders(set); } assertEquals(1, r.getHeaders().size()); assertEquals(200000L, r.getLastModified()); { Set<ResponseHeader> set = new TreeSet<ResponseHeader>(); set.add(new ResponseHeaderImpl("Last-Modified", new String[] { DateUtil.formatDate(new Date(310000L)) })); set.add(new ResponseHeaderImpl("User-Agent", new String[] { "Pinoccio" })); r.addHeaders(set); } assertEquals(2, r.getHeaders().size()); int ii = 0; for (ResponseHeader h : r.getHeaders()) { ii++; if (ii == 1) { assertEquals("Last-Modified", h.getName()); assertEquals(Arrays.toString(new String[] { DateUtil.formatDate(new Date(310000L)) }), Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("User-Agent", h.getName()); assertEquals(Arrays.toString(new String[] { "Pinoccio" }), Arrays.toString(h.getValues())); } } r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", mockStorage.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } assertFalse(r.hasEnded()); assertNull(r.getEndState()); assertEquals(0L, observer.getHits()); r.setEndState(ResponseStateOk.getInstance()); assertEquals(ResponseStateOk.getInstance(), r.getEndState()); assertTrue(r.hasEnded()); assertEquals(1L, observer.getHits()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
00
Code Sample 1: protected void fixupCategoryAncestry(Context context) throws DataStoreException { Connection db = null; Statement s = null; try { db = context.getConnection(); db.setAutoCommit(false); s = db.createStatement(); s.executeUpdate("delete from category_ancestry"); walkTreeFixing(db, CATEGORYROOT); db.commit(); context.put(Form.ACTIONEXECUTEDTOKEN, "Category Ancestry regenerated"); } catch (SQLException sex) { try { db.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw new DataStoreException("Failed to refresh category ancestry"); } finally { if (s != null) { try { s.close(); } catch (SQLException e) { e.printStackTrace(); } } if (db != null) { context.releaseConnection(db); } } } Code Sample 2: public final void propertyChange(final PropertyChangeEvent event) { if (fChecker != null && event.getProperty().equals(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY)) { if (fUserDictionary != null) { fChecker.removeDictionary(fUserDictionary); fUserDictionary = null; } final String file = (String) event.getNewValue(); if (file.length() > 0) { try { final URL url = new URL("file", null, file); InputStream stream = url.openStream(); if (stream != null) { try { fUserDictionary = new PersistentSpellDictionary(url); fChecker.addDictionary(fUserDictionary); } finally { stream.close(); } } } catch (MalformedURLException exception) { } catch (IOException exception) { } } } }
11
Code Sample 1: public void fileCopy2(File inFile, File outFile) throws Exception { try { FileChannel srcChannel = new FileInputStream(inFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { throw new Exception("Could not copy file: " + inFile.getName()); } } Code Sample 2: public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } }
00
Code Sample 1: public String getImageURL(String text) { String imgURL = ""; try { URL url = new URL("http://images.search.yahoo.com/search/images?p=" + URLEncoder.encode(text)); URLConnection connection = url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); String line; Pattern imgPattern = Pattern.compile("isrc=\"([^\"]*)\""); while ((line = in.readLine()) != null) { Matcher match = imgPattern.matcher(line); if (match.find()) { imgURL = match.group(1); break; } } in.close(); } catch (Exception e) { } return imgURL; } Code Sample 2: public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
00
Code Sample 1: public void process(String dir) { String[] list = new File(dir).list(); if (list == null) return; int n = list.length; long[] bubblesort = new long[list.length + 1]; if (!statustext) { IJ.log("Current Directory is: " + dir); IJ.log(" "); IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick); IJ.log(" "); } for (int i = 0; i < n; i++) { IJ.showStatus(i + "/" + n); File f = new File(dir + list[i]); if (!f.isDirectory()) { ImagePlus img = new Opener().openImage(dir, list[i]); if (img != null && img.getStackSize() == 1) { if (!scoutengine(img)) return; if (!statustext) { IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase); } int lastDigit = whichcase.length() - 1; while (lastDigit > 0) { if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break; } if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1); bubblesort[i] = Long.parseLong(whichcase); } } } if (statussorta || statussortd || statustext) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (statussorta) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } else { if (bubblesort[i] < bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } } IJ.log(" "); for (int i = 0; i < n; i++) { if (!statustext) { IJ.log(list[i] + " / " + bubblesort[i]); } else { IJ.log(dir + list[i]); } } } if (open_as_stack || only_images) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } if (only_images) { Opener o = new Opener(); int counter = 0; IJ.log(" "); for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; else { ImagePlus imp = o.openImage(path); counter++; if (imp != null) { IJ.log(counter + " + " + path); imp.show(); } else IJ.log(counter + " - " + path); } } return; } int width = 0, height = 0, type = 0; ImageStack stack = null; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int k = 0; try { for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; if (list[i].endsWith(".txt")) continue; ImagePlus imp = new Opener().openImage(path); if (imp != null && stack == null) { width = imp.getWidth(); height = imp.getHeight(); type = imp.getType(); ColorModel cm = imp.getProcessor().getColorModel(); if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm); } if (stack != null) k = stack.getSize() + 1; IJ.showStatus(k + "/" + n); IJ.showProgress((double) k / n); if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else { ImageProcessor ip = imp.getProcessor(); if (grayscale) ip = ip.convertToByte(true); if (halfSize) ip = ip.resize(width / 2, height / 2); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); String label = imp.getTitle(); String info = (String) imp.getProperty("Info"); if (info != null) label += "\n" + info; stack.addSlice(label, ip); } System.gc(); } } catch (OutOfMemoryError e) { IJ.outOfMemory("FolderOpener"); stack.trim(); } if (stack != null && stack.getSize() > 0) { ImagePlus imp2 = new ImagePlus("Stack", stack); if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max); imp2.show(); } IJ.showProgress(1.0); } } Code Sample 2: public static String SHA1(String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: private static <OS extends OutputStream> OS getUnzipAndDecodeOutputStream(InputStream inputStream, final OS outputStream) { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final List<Throwable> ungzipThreadThrowableList = new LinkedList<Throwable>(); Writer decoderWriter = null; Thread ungzipThread = null; try { final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); ungzipThread = new Thread(new Runnable() { public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } }); decoderWriter = Base64.newDecoder(pipedOutputStream); ungzipThread.start(); IOUtils.copy(inputStream, decoderWriter, DVK_MESSAGE_CHARSET); decoderWriter.flush(); pipedOutputStream.flush(); } catch (IOException e) { throw new RuntimeException("failed to unzip and decode input", e); } finally { IOUtils.closeQuietly(decoderWriter); IOUtils.closeQuietly(pipedOutputStream); if (ungzipThread != null) { try { ungzipThread.join(); } catch (InterruptedException ie) { throw new RuntimeException("thread interrupted while for ungzip thread to finish", ie); } } } if (!ungzipThreadThrowableList.isEmpty()) { throw new RuntimeException("ungzip failed", ungzipThreadThrowableList.get(0)); } return outputStream; }
11
Code Sample 1: public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: @Override public void remove(int disciplinaId) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "delete from Disciplina where id = ?"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setInt(1, disciplinaId); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de Revendedor no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } } Code Sample 2: public static List<String> unZip(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream); ZipArchiveEntry entry = in.getNextZipEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextZipEntry(); } in.close(); return result; }
11
Code Sample 1: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) abort("FileCopy: no such source file: " + from_file.getName()); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_file.getName()); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_file.getName()); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_file.getName()); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { e.printStackTrace(); } } if (to != null) { try { to.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
11
Code Sample 1: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; } Code Sample 2: private void zip(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } }
11
Code Sample 1: public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; } Code Sample 2: public static boolean checkEncryptedPassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); default: return false; } }
00
Code Sample 1: public boolean visar() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ps = null; Date fechaSystem = new Date(); DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd"); DateFormat hhmmss = new SimpleDateFormat("HHmmss"); DateFormat sss = new SimpleDateFormat("S"); String ss = sss.format(fechaSystem); if (ss.length() > 2) { ss = ss.substring(0, 2); } boolean visado = false; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentenciaSql = "UPDATE BZMODIF SET FZJCUSVI=?, FZJFVISA=?, FZJHVISA=?" + ((hayVisadoExtracto) ? ", FZJIEXTR=?" : "") + ((hayVisadoRemitente) ? ", FZJIREMI=?" : "") + " WHERE FZJCENSA='E' AND FZJCAGCO=? AND FZJNUMEN=? AND FZJANOEN=? AND FZJFMODI=? AND FZJHMODI=?"; ps = conn.prepareStatement(sentenciaSql); ps.setString(1, usuarioVisado); ps.setInt(2, Integer.parseInt(aaaammdd.format(fechaSystem))); ps.setInt(3, Integer.parseInt(hhmmss.format(fechaSystem) + ss)); int contador = 4; if (hayVisadoExtracto) { ps.setString(contador++, "X"); } if (hayVisadoRemitente) { ps.setString(contador++, "X"); } ps.setInt(contador++, oficina); ps.setInt(contador++, numeroRegistro); ps.setInt(contador++, anoEntrada); ps.setString(contador++, fechaModificacion); ps.setString(contador++, horaModificacion); int registrosAfectados = ps.executeUpdate(); if (registrosAfectados > 0 && !hayVisadoExtracto && !hayVisadoRemitente) { visado = true; } if (registrosAfectados > 0 && (hayVisadoExtracto || hayVisadoRemitente)) { boolean generado = generarBZVISAD(conn, Integer.parseInt(aaaammdd.format(fechaSystem)), Integer.parseInt(hhmmss.format(fechaSystem) + ss)); if (generado) { visado = actualizarBZENTRA(conn); } String rem = ""; String com = ""; if (hayVisadoRemitente) { if (!remitente.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1, entidad2 + ""); valor.remove(); } } else { if (!altres.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1Old, entidad2Old + ""); valor.remove(); } } if (hayVisadoExtracto) { com = extracto; } else { com = comentario; } try { Class t = Class.forName("es.caib.regweb.module.PluginHook"); Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class, String.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class }; Object[] params = { "V", new Integer(anoEntrada), new Integer(numeroRegistro), new Integer(oficina), new Integer(fechaDocumento), rem, com, tipoDocumento, new Integer(fechaRegistro), new Integer(fzacagge), fora, new Integer(destinatario), idioma, null, null, null, null, null, null, null }; java.lang.reflect.Method metodo = t.getMethod("entrada", partypes); metodo.invoke(null, params); } catch (IllegalAccessException iae) { } catch (IllegalArgumentException iae) { } catch (InvocationTargetException ite) { } catch (NullPointerException npe) { } catch (ExceptionInInitializerError eiie) { } catch (NoSuchMethodException nsme) { } catch (SecurityException se) { } catch (LinkageError le) { } catch (ClassNotFoundException le) { } } conn.commit(); int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss); String Stringsss = sss.format(fechaSystem); switch(Stringsss.length()) { case (1): Stringsss = "00" + Stringsss; break; case (2): Stringsss = "0" + Stringsss; break; } int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss); int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem)); logLopdBZMODIF("UPDATE", sessioEjb.getCallerPrincipal().getName().toUpperCase(), fzafsis, horamili, 'E', numeroRegistro, anoEntrada, oficina, Integer.parseInt(fechaModificacion), Integer.parseInt(horaModificacion)); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); visado = false; try { if (conn != null) conn.rollback(); else System.out.println("ERROR: No es pot fer rollback sense connexió!"); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } } finally { ToolsBD.closeConn(conn, ps, null); } return visado; } Code Sample 2: public static void copy(String pstrFileFrom, String pstrFileTo) { try { FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel(); FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: public T08OTSDTMInterpositionUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); } Code Sample 2: public OperandToken evaluate(Token[] operands, GlobalValues globals) { String s = ""; String lineFile = ""; ; if (getNArgIn(operands) != 1) throwMathLibException("urlread: number of arguments < 1"); if (!(operands[0] instanceof CharToken)) throwMathLibException("urlread: argument must be String"); String urlString = ((CharToken) operands[0]).toString(); URL url = null; try { url = new URL(urlString); } catch (Exception e) { throwMathLibException("urlread: malformed url"); } try { BufferedReader inReader = new BufferedReader(new InputStreamReader(url.openStream())); while ((lineFile = inReader.readLine()) != null) { s += lineFile + "\n"; } inReader.close(); } catch (Exception e) { throwMathLibException("urlread: error input stream"); } return new CharToken(s); }
00
Code Sample 1: private String getMd5(String base64image) { String token = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(base64image.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); token = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return token; } Code Sample 2: public void insertProfile() throws ClassNotFoundException, SQLException { Connection connection = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(this.url); connection.setAutoCommit(false); String query1 = "INSERT INTO customers(name,password) VALUES(?,?)"; ps1 = connection.prepareStatement(query1); ps1.setString(1, this.name); ps1.setString(2, this.password); String query2 = "INSERT INTO customer_roles(name,role_name) VALUES(?,?)"; ps2 = connection.prepareStatement(query2); ps2.setString(1, this.name); ps2.setString(2, "user"); String query3 = "INSERT INTO customers_profile(name,first_name,middle_name,last_name,address1,address2,city,post_box,email,country)" + "VALUES(?,?,?,?,?,?,?,?,?,?)"; ps3 = connection.prepareStatement(query3); ps3.setString(1, this.name); ps3.setString(2, this.firstName); ps3.setString(3, this.middleName); ps3.setString(4, this.lastName); ps3.setString(5, this.address1); ps3.setString(6, this.address2); ps3.setString(7, this.city); ps3.setString(8, this.postBox); ps3.setString(9, this.email); ps3.setString(10, this.country); ps1.executeUpdate(); ps2.executeUpdate(); ps3.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { this.connection.close(); } catch (Exception ex) { } try { ps1.close(); } catch (Exception ex) { } try { ps2.close(); } catch (Exception ex) { } try { ps3.close(); } catch (Exception ex) { } } }
11
Code Sample 1: private void copyResource(String resource, File targetDir) { InputStream is = FragmentFileSetTest.class.getResourceAsStream(resource); Assume.assumeNotNull(is); int i = resource.lastIndexOf("/"); String filename; if (i == -1) { filename = resource; } else { filename = resource.substring(i + 1); } try { FileOutputStream fos = new FileOutputStream(new File(targetDir, filename)); IOUtils.copy(is, fos); fos.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } Code Sample 2: public static void copyFile(File sourceFile, File targetFile) throws FileCopyingException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileCopyingException(exceptionMessage, ioException); } }
00
Code Sample 1: protected void initConnection() { connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Range", "bytes=" + downloadedSize + "-"); prepareConnectionBeforeConnect(); connection.connect(); } catch (IOException e) { status = STATUS_ERROR; Logger.getRootLogger().error("problem in connection", e); } } Code Sample 2: public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); }
00
Code Sample 1: private void sortWhats(String[] labels, int[] whats, String simplifyString) { int n = whats.length; boolean swapped; do { swapped = false; for (int i = 0; i < n - 1; i++) { int i0_pos = simplifyString.indexOf(labels[whats[i]]); int i1_pos = simplifyString.indexOf(labels[whats[i + 1]]); if (i0_pos > i1_pos) { int temp = whats[i]; whats[i] = whats[i + 1]; whats[i + 1] = temp; swapped = true; } } } while (swapped); } Code Sample 2: public static boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; }
00
Code Sample 1: private Set read() throws IOException { URL url = new URL(urlPrefix + channelId + ".dat"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); Set programs = new HashSet(); while (line != null) { String[] values = line.split("~"); if (values.length != 23) { throw new RuntimeException("error: incorrect format for radiotimes information"); } Program program = new RadioTimesProgram(values, channelId); programs.add(program); line = in.readLine(); } return programs; } Code Sample 2: public static void copy(File srcFile, File destFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); final byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } finally { try { if (in != null) in.close(); } catch (IOException ioe) { } try { if (out != null) out.close(); } catch (IOException ioe) { } } }
11
Code Sample 1: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } } Code Sample 2: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
00
Code Sample 1: public static byte[] computeMD5(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(s.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } } Code Sample 2: public static void main(String[] args) throws IOException { long readfilelen = 0; BufferedRandomAccessFile brafReadFile, brafWriteFile; brafReadFile = new BufferedRandomAccessFile("C:\\WINNT\\Fonts\\STKAITI.TTF"); readfilelen = brafReadFile.initfilelen; brafWriteFile = new BufferedRandomAccessFile(".\\STKAITI.001", "rw", 10); byte buf[] = new byte[1024]; int readcount; long start = System.currentTimeMillis(); while ((readcount = brafReadFile.read(buf)) != -1) { brafWriteFile.write(buf, 0, readcount); } brafWriteFile.close(); brafReadFile.close(); System.out.println("BufferedRandomAccessFile Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); java.io.FileInputStream fdin = new java.io.FileInputStream("C:\\WINNT\\Fonts\\STKAITI.TTF"); java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fdin, 1024); java.io.DataInputStream dis = new java.io.DataInputStream(bis); java.io.FileOutputStream fdout = new java.io.FileOutputStream(".\\STKAITI.002"); java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(fdout, 1024); java.io.DataOutputStream dos = new java.io.DataOutputStream(bos); start = System.currentTimeMillis(); for (int i = 0; i < readfilelen; i++) { dos.write(dis.readByte()); } dos.close(); dis.close(); System.out.println("DataBufferedios Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); }
11
Code Sample 1: public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
00
Code Sample 1: public static String send(String method, String url, Map<String, String> paramMap, File file, String encoding) throws HttpServerStatusException { Log.i(TAG, "url:" + url); boolean bVisitOK = false; int tryCnt = 0; String result = ""; while (!bVisitOK && (tryCnt++ < MAXTRYCNT)) { try { HttpRequestBase base = getExecuteMethod(method, url, paramMap, file); HttpResponse response = client.execute(base, localContext); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { result = readByteStream(entity.getContent(), encoding); entity.consumeContent(); } if (status == 200) { return result; } else { throw new HttpServerStatusException(status, result); } } catch (HttpServerStatusException e) { throw e; } catch (IllegalStateException e) { bVisitOK = false; Log.e(TAG, e.toString()); } catch (IOException e) { bVisitOK = false; Log.e(TAG, e.toString()); } } return result; } Code Sample 2: public static boolean copyFile(File src, File target) throws IOException { if (src == null || target == null || !src.exists()) return false; if (!target.exists()) if (!createNewFile(target)) return false; InputStream ins = new BufferedInputStream(new FileInputStream(src)); OutputStream ops = new BufferedOutputStream(new FileOutputStream(target)); int b; while (-1 != (b = ins.read())) ops.write(b); Streams.safeClose(ins); Streams.safeFlush(ops); Streams.safeClose(ops); return target.setLastModified(src.lastModified()); }
00
Code Sample 1: @Override List<String> HttpGet(URL url) throws IOException { List<String> responseList = new ArrayList<String>(); Logger.getInstance().logInfo("HTTP GET: " + url, null, getGatewayId()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(20000); con.setAllowUserInteraction(false); responseList.add(con.getResponseCode() + " " + con.getResponseMessage()); InputStream inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) responseList.add(inputLine); in.close(); return responseList; } Code Sample 2: private ParserFileReader createParserFileReader(final FromNetRecord record) throws IOException { final String strUrl = record.getStrUrl(); ParserFileReader parserFileReader; try { parserFileReader = parserFileReaderFactory.create(strUrl); } catch (Exception exception) { _log.error("can not create reader for \"" + strUrl + "\"", exception); parserFileReader = null; } url = parserFileReaderFactory.getUrl(); if (parserFileReader != null) { parserFileReader.mark(); final String outFileName = urlToFile("runtime/tests", url, ""); final File outFile = new File(outFileName); outFile.getParentFile().mkdirs(); final Writer writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"); int readed; while ((readed = parserFileReader.read()) != -1) { writer.write(readed); } writer.close(); parserFileReader.reset(); } return parserFileReader; }
11
Code Sample 1: public static int deleteHedgeCustTrade() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_HEDGE_CUSTTRADE "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; } Code Sample 2: public static void importDocumentLines(Connection conn, String originDocumentID, String destinationDocumentID) throws SQLException { boolean defaultAutoCommit = conn.getAutoCommit(); String sqlQuery = "select ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice from tbl_DocumentItem where DocumentID=?"; String sqlInsert = "insert into tbl_DocumentItem (ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice,DocumentID) values (?,?,?,?,?,?,?,?,?)"; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; try { pstmt1 = conn.prepareStatement(sqlQuery); pstmt2 = conn.prepareStatement(sqlInsert); conn.setAutoCommit(false); pstmt1.setString(1, originDocumentID); ResultSet rs = pstmt1.executeQuery(); while (rs.next()) { pstmt2.setInt(1, rs.getInt(1)); pstmt2.setString(2, rs.getString(2)); pstmt2.setDouble(3, rs.getDouble(3)); pstmt2.setDouble(4, rs.getDouble(4)); pstmt2.setDouble(5, rs.getDouble(5)); pstmt2.setDouble(6, rs.getDouble(6)); pstmt2.setDouble(7, rs.getDouble(7)); pstmt2.setDouble(8, rs.getDouble(8)); pstmt2.setString(9, destinationDocumentID); pstmt2.executeUpdate(); } rs.close(); conn.commit(); } catch (SQLException ex) { conn.rollback(); } finally { conn.setAutoCommit(defaultAutoCommit); if (pstmt1 != null) pstmt1.close(); if (pstmt2 != null) pstmt2.close(); } }
11
Code Sample 1: public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } } Code Sample 2: public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
11
Code Sample 1: public void end() throws Exception { handle.waitFor(); Calendar endTime = Calendar.getInstance(); File resultsDir = new File(runDir, "results"); if (!resultsDir.isDirectory()) throw new Exception("The results directory not found!"); String resHtml = null; String resTxt = null; String[] resultFiles = resultsDir.list(); for (String resultFile : resultFiles) { if (resultFile.indexOf("html") >= 0) resHtml = resultFile; else if (resultFile.indexOf("txt") >= 0) resTxt = resultFile; } if (resHtml == null) throw new IOException("SPECweb2005 output (html) file not found"); if (resTxt == null) throw new IOException("SPECweb2005 output (txt) file not found"); File resultHtml = new File(resultsDir, resHtml); copyFile(resultHtml.getAbsolutePath(), runDir + "SPECWeb-result.html", false); BufferedReader reader = new BufferedReader(new FileReader(new File(resultsDir, resTxt))); logger.fine("Text file: " + resultsDir + resTxt); Writer writer = new FileWriter(runDir + "summary.xml"); SummaryParser parser = new SummaryParser(getRunId(), startTime, endTime, logger); parser.convert(reader, writer); writer.close(); reader.close(); } Code Sample 2: public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public static Vector webService(String siteUrl, String login, String password, String table, String station, String element, String dayFrom, String dayTo, String filePath) throws Exception { Service service = new Service(); Call call = (Call) service.createCall(); if (login != null) { call.setUsername(login); if (password != null) { call.setPassword(password); } System.err.println("Info: authentication user=" + login + " passwd=" + password + " at " + siteUrl); } call.setTargetEndpointAddress(new URL(siteUrl)); call.setOperationName("syncData"); Vector exportList = (Vector) call.invoke(new Object[] { table, station, element, dayFrom, dayTo }); if (exportList != null) { for (int k = 0; k < exportList.size(); k++) { HashMap exportDescr = (HashMap) exportList.get(k); String url = (String) exportDescr.get("fileName"); log.debug("result URL is " + url); String fileName = null; URL dataurl = new URL(url); String filePart = dataurl.getFile(); if (filePart == null) { throw new Exception("Error: file part in the data URL is null"); } else { fileName = filePart.substring(filePart.lastIndexOf("/") < 0 ? 0 : filePart.lastIndexOf("/") + 1); if (filePath != null) { fileName = filePath + fileName; } log.debug("local file name is " + fileName); } FileOutputStream fos = new FileOutputStream(fileName); if (fos == null) { throw new Exception("Error: file output stream is null"); } InputStream strm = dataurl.openStream(); if (strm == null) { throw new Exception("Error: data input stream is null"); } else { int c; while ((c = strm.read()) != -1) { fos.write(c); } } strm.close(); fos.close(); File file = new File(fileName); exportDescr.put("fileName", file.getCanonicalPath()); } } return exportList; } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: public static boolean copyFile(String sourceFileName, String destFileName) { FileChannel ic = null; FileChannel oc = null; try { ic = new FileInputStream(sourceFileName).getChannel(); oc = new FileOutputStream(destFileName).getChannel(); ic.transferTo(0, ic.size(), oc); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { ic.close(); } catch (IOException e) { e.printStackTrace(); } try { oc.close(); } catch (IOException e) { e.printStackTrace(); } } return false; } Code Sample 2: @Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { try { if (vtf == null) { LOG.debug("Serializing from database"); existDocument.stream(out); } else { LOG.debug("Serializing from buffer"); InputStream is = vtf.getByteStream(); IOUtils.copy(is, out); out.flush(); IOUtils.closeQuietly(is); vtf.delete(); vtf = null; } } catch (PermissionDeniedException e) { LOG.debug(e.getMessage()); throw new NotAuthorizedException(this); } finally { IOUtils.closeQuietly(out); } }
11
Code Sample 1: public String hash(String plainTextPassword) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(plainTextPassword.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(org.jboss.seam.util.Hex.encodeHex(rawHash)); } catch (NoSuchAlgorithmException e) { log.error("Digest algorithm #0 to calculate the password hash will not be supported.", digestAlgorithm); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { log.error("The Character Encoding #0 is not supported", charset); throw new RuntimeException(e); } } Code Sample 2: public boolean verify(String digest, String password) throws NoSuchAlgorithmException { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{CRYPT}", 0, 7)) { digest = digest.substring(7); return UnixCrypt.matches(digest, password); } else if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } MessageDigest msgDigest = MessageDigest.getInstance(alg); byte[][] hs = split(Base64.decode(digest.toCharArray()), size); byte[] hash = hs[0]; byte[] salt = hs[1]; msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); return msgDigest.isEqual(hash, pwhash); }
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 void testTransactions0010() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0010 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i + ((j - 1) * rowsToAdd)); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) { i -= rowsToAdd; } assertEquals(rs.getString(1).trim().length(), i); } assertEquals(count, (2 * rowsToAdd)); stmt.close(); pstmt.close(); con.setAutoCommit(true); }
00
Code Sample 1: public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2010May cb = new AcmSearchresultPageParser_2010May(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartPositions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartPositions().get(i); System.out.println(i + "pos= " + m); } } Code Sample 2: public Object run() { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(buf.toString().getBytes()); byte[] data = digest.digest(); serialNum = new BASE64Encoder().encode(data); return serialNum; } catch (NoSuchAlgorithmException exp) { BootSecurityManager.securityLogger.log(Level.SEVERE, exp.getMessage(), exp); return buf.toString(); } }
00
Code Sample 1: public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); } Code Sample 2: public String load(URL url) throws LoaderException { log.debug("loading content"); log.trace("opening connection: " + url); BufferedReader in = null; URLConnection conn = null; try { conn = url.openConnection(); in = null; if (encodedProxyLogin != null) { conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedProxyLogin); } } catch (IOException ioe) { log.warn("Error create connection"); throw new LoaderException("Error create connection", ioe); } log.trace("connection opened, reading ... "); StringBuilder buffer = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } } catch (IOException ioe) { log.warn("Error loading content"); throw new LoaderException("Error reading content. ", ioe); } finally { try { in.close(); } catch (Exception e) { } } log.debug("content loaded"); return buffer.toString(); }
00
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public static String hashClientPassword(String algorithm, String password, String salt) throws IllegalArgumentException, DruidSafeRuntimeException { if (algorithm == null) { throw new IllegalArgumentException("THE ALGORITHM MUST NOT BE NULL"); } if (password == null) { throw new IllegalArgumentException("THE PASSWORD MUST NOT BE NULL"); } if (salt == null) { salt = ""; } String result = null; try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(password.getBytes()); md.update(salt.getBytes()); result = SecurityHelper.byteArrayToHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new DruidSafeRuntimeException(e); } return result; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static ArrayList<String> remoteCall(Map<String, String> dataDict) { ArrayList<String> result = new ArrayList<String>(); String encodedData = ""; for (String key : dataDict.keySet()) { String encodedSegment = ""; String value = dataDict.get(key); if (value == null) continue; try { encodedSegment = key + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (encodedData.length() > 0) { encodedData += "&"; } encodedData += encodedSegment; } try { URL url = new URL(baseURL + encodedData); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.add(line); System.out.println("GOT: " + line); } reader.close(); result.remove(0); if (result.size() != 0) { if (!result.get(result.size() - 1).equals("DONE")) { result.clear(); } else { result.remove(result.size() - 1); } } } catch (MalformedURLException e) { } catch (IOException e) { } return result; }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public synchronized void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CacheEntry entry = null; Tenant tenant = null; if (!tenantInfo.getTenants().isEmpty()) { tenant = tenantInfo.getMatchingTenant(request); if (tenant == null) { tenant = tenantInfo.getTenants().get(0); } entry = tenantToCacheEntry.get(tenant.getName()); } else { entry = cacheEntry; } if (entry == null) { File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); tempDir = new File(tempDir, "pustefix-sitemap-cache"); if (!tempDir.exists()) { tempDir.mkdirs(); } entry = new CacheEntry(); entry.file = new File(tempDir, "sitemap" + (tenant == null ? "" : "-" + tenant.getName()) + ".xml"); try { String host = AbstractPustefixRequestHandler.getServerName(request); Document doc = getSearchEngineSitemap(tenant, host); Transformer trf = TransformerFactory.newInstance().newTransformer(); trf.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream out = new FileOutputStream(entry.file); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException x) { throw new RuntimeException("Can't create message digest", x); } DigestOutputStream digestOutput = new DigestOutputStream(out, digest); trf.transform(new DOMSource(doc), new StreamResult(digestOutput)); digestOutput.close(); byte[] digestBytes = digest.digest(); entry.etag = MD5Utils.byteToHex(digestBytes); } catch (Exception x) { throw new ServletException("Error creating sitemap", x); } } String reqETag = request.getHeader("If-None-Match"); if (reqETag != null) { if (entry.etag.equals(reqETag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } long reqMod = request.getDateHeader("If-Modified-Since"); if (reqMod != -1) { if (entry.file.lastModified() < reqMod + 1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } response.setContentType("application/xml"); response.setContentLength((int) entry.file.length()); response.setDateHeader("Last-Modified", entry.file.lastModified()); response.setHeader("ETag", entry.etag); OutputStream out = new BufferedOutputStream(response.getOutputStream()); InputStream in = new FileInputStream(entry.file); int bytes_read; byte[] buffer = new byte[8]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.flush(); in.close(); out.close(); }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); } Code Sample 2: public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } }
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: private PluginInfo loadPluginInfo(URL filename) throws PluginNotFoundException { if (filename == null) return null; BufferedReader in = null; InputStream is = null; String mainClass = null; String u = filename.toString(); PluginInfo pi = new PluginInfo(); URL url; try { url = new URL("jar:" + u + "!/"); } catch (MalformedURLException mue) { throw new PluginNotFoundException(mue); } pi.setURL(filename); HashMap names = new HashMap(); boolean seemsOK = false; for (int tries = 0; (tries <= 5) && (!seemsOK); tries++) { try { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarConnection.setUseCaches(false); JarFile jf = jarConnection.getJarFile(); is = jf.getInputStream(jf.getJarEntry("META-INF/MANIFEST.MF")); in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) { if (line.startsWith("Frostplugin-Main-Class: ")) { mainClass = line.substring("Frostplugin-Main-Class: ".length()).trim(); pi.setMainClass(mainClass); logger.log(Level.SEVERE, "Found plugin main class " + mainClass + " from manifest"); } } is = jf.getInputStream(jf.getJarEntry("pluginname.properties")); in = new BufferedReader(new InputStreamReader(is)); while ((line = in.readLine()) != null) { if (line.startsWith("#")) { continue; } if (line.length() == 0) { continue; } String[] sa = line.split("=", 2); names.put(sa[0], sa[1]); pi.setPluginNames(names); } seemsOK = true; } catch (Exception e) { if (tries >= 5) throw new PluginNotFoundException("Initialization error:" + filename, e); try { Thread.sleep(100); } catch (Exception ee) { } } finally { try { if (is != null) is.close(); if (in != null) in.close(); } catch (IOException ioe) { } } } return pi; }
11
Code Sample 1: private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read); inFile.close(); } Code Sample 2: @Override public File fetchHSMFile(String fsID, String filePath) throws HSMException { log.debug("fetchHSMFile called with fsID=" + fsID + ", filePath=" + filePath); if (absIncomingDir.mkdirs()) { log.info("M-WRITE " + absIncomingDir); } File tarFile; try { tarFile = File.createTempFile("hsm_", ".tar", absIncomingDir); } catch (IOException x) { throw new HSMException("Failed to create temp file in " + absIncomingDir, x); } log.info("Fetching " + filePath + " from cloud storage"); FileOutputStream fos = null; try { if (s3 == null) createClient(); S3Object object = s3.getObject(new GetObjectRequest(bucketName, filePath)); fos = new FileOutputStream(tarFile); IOUtils.copy(object.getObjectContent(), fos); } catch (AmazonClientException ace) { s3 = null; throw new HSMException("Could not list objects for: " + filePath, ace); } catch (Exception x) { throw new HSMException("Failed to retrieve " + filePath, x); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.error("Couldn't close output stream for: " + tarFile); } } } return tarFile; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void copyFile(String from, String to) throws IOException { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: public void testManageSources() throws Exception { this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); final File implementationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); final File specificationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("IllegalImplementationSource.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); IOUtils.copy(this.getClass().getResourceAsStream("IllegalSpecificationSource.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); try { this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } try { this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } this.getTestTool().setProfile("DOES_NOT_EXIST"); this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), this.getTestSourcesDirectory()); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private static String getSignature(String data) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return "FFFFFFFFFFFFFFFF"; } md.update(data.getBytes()); StringBuffer sb = new StringBuffer(); byte[] sign = md.digest(); for (int i = 0; i < sign.length; i++) { byte b = sign[i]; int in = (int) b; if (in < 0) in = 127 - b; String hex = Integer.toHexString(in).toUpperCase(); if (hex.length() == 1) hex = "0" + hex; sb.append(hex); } return sb.toString(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: 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: @Override public void doExecute(String[] args) { if (args.length != 2) { printUsage(); } else { int fileNo = 0; try { fileNo = Integer.parseInt(args[1]) - 1; } catch (NumberFormatException e) { printUsage(); return; } if (fileNo < 0) { printUsage(); return; } StorageFile[] files = (StorageFile[]) ctx.getRemoteDir().listFiles(); try { StorageFile file = files[fileNo]; File outFile = getOutFile(file); FileOutputStream out = new FileOutputStream(outFile); InputStream in = file.openStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); afterSave(outFile); if (outFile.exists()) { print("File written to: " + outFile.getAbsolutePath()); } } catch (IOException e) { printError("Failed to load file. " + e.getMessage()); } catch (Exception e) { printUsage(); return; } } } Code Sample 2: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
11
Code Sample 1: public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); }
00
Code Sample 1: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { } } try { digest.update(data.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { } return encodeHex(digest.digest()); } Code Sample 2: public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception { URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid()); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; boolean chargerLyrics = false; StringBuffer sb = new StringBuffer(""); String lyrics = null; while ((ligne = br.readLine()) != null) { log.debug("==> " + ligne); if (chargerLyrics && ligne.indexOf("<center>") != -1) { break; } if (chargerLyrics) { sb.append(ligne.trim()); } if (!chargerLyrics && ligne.indexOf("<center>") != -1) { chargerLyrics = true; } } lyrics = sb.toString(); lyrics = lyrics.replaceAll("<br>", "\n").trim(); log.debug("Parole : " + lyrics); tb.setLyrics(lyrics); br.close(); httpStream.close(); }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } } Code Sample 2: private static void copyContent(final File srcFile, final File dstFile, final boolean gzipContent) throws IOException { final File dstFolder = dstFile.getParentFile(); dstFolder.mkdirs(); if (!dstFolder.exists()) { throw new RuntimeException("Unable to create the folder " + dstFolder.getAbsolutePath()); } final InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(dstFile); if (gzipContent) { out = new GZIPOutputStream(out); } try { final byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { in.close(); out.close(); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) startWindow(prop); else if (tag.equals("splitpanel")) startSplitPanel(prop); else if (tag.equals("desktoppane")) startDesktopPane(prop); else if (tag.equals("tabcontrol")) startTabcontrol(prop); else if (tag.equals("panel")) startPanel(prop); else if (tag.equals("statusbar")) startStatusbar(prop); else if (tag.equals("toolbar")) startToolbar(prop); else if (tag.equals("toolbarbutton")) startToolbarbutton(prop); else if (tag.equals("menu")) startMenu(prop); else if (tag.equals("menuitem")) startMenuitem(prop); else if (tag.equals("separator")) menu.addSeparator(); else if (tag.equals("choice")) startChoice(prop); else if (tag.equals("list")) startList(prop); else if (tag.equals("option")) startOption(prop); else if (tag.equals("label")) startLabel(prop); else if (tag.equals("button")) startButton(prop); else if (tag.equals("groupbox")) startGroupbox(prop); else if (tag.equals("radiobutton")) startRadioButton(prop); else if (tag.equals("checkbox")) startCheckbox(prop); else if (tag.equals("image")) startImage(prop); else if (tag.equals("textarea")) startTextArea(prop); else if (tag.equals("singlelineedit")) startSingleLineEdit(prop); else if (tag.equals("treeview")) startTreeview(prop); else if (tag.equals("treeitem")) startTreeitem(prop); else if (tag.equals("table")) startTable(prop); else if (tag.equals("header")) startHeader(prop); else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.addRow(); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("rmbmenuitem")) { if (prop == null) { System.err.println("datawindow.menuitem without properties"); return; } String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); JMenuItem mi = new JMenuItem(label); mi.setActionCommand(action); mi.addActionListener(win); rmbmenu.add(mi); } else if (tag.equals("rmbseparator")) { rmbmenu.addSeparator(); } else if (tag.equals("script")) { win.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; win.script += buffer + "\n"; } r.close(); win.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[win] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
00
Code Sample 1: public void loadLicenceText() { try { URL url = this.getClass().getResource("/licences/" + this.files[this.licence_text_id]); InputStreamReader ins = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(ins); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } this.licence_text = sb.toString(); } catch (Exception ex) { System.out.println("LicenceInfo::error reading. Ex: " + ex); ex.printStackTrace(); } } Code Sample 2: public void testJTLM_publish100() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.DEFAULT_OPTIONS); AlignmentType[] alignments = new AlignmentType[] { AlignmentType.bitPacked, AlignmentType.byteAligned, AlignmentType.preCompress, AlignmentType.compress }; for (AlignmentType alignment : alignments) { Transmogrifier encoder = new Transmogrifier(); EXIDecoder decoder = new EXIDecoder(999); Scanner scanner; InputSource inputSource; encoder.setAlignmentType(alignment); decoder.setAlignmentType(alignment); encoder.setEXISchema(grammarCache); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/JTLM/publish100.xml"); inputSource = new InputSource(url.toString()); inputSource.setByteStream(url.openStream()); byte[] bts; int n_events, n_texts; encoder.encode(inputSource); bts = baos.toByteArray(); decoder.setEXISchema(grammarCache); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(publish100_centennials[n], exiEvent.getCharacters().makeString()); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(10610, n_events); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); } Code Sample 2: public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); }
00
Code Sample 1: public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); } Code Sample 2: @Test public void test_lookupType_NonExistingName() throws Exception { URL url = new URL(baseUrl + "/lookupType/blah-blah"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rowset/>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); }
00
Code Sample 1: @Override public String getLatestApplicationVersion() { String latestVersion = null; String latestVersionInfoURL = "http://movie-browser.googlecode.com/svn/site/latest"; LOGGER.info("Checking latest version info from: " + latestVersionInfoURL); BufferedReader in = null; try { LOGGER.info("Fetcing latest version info from: " + latestVersionInfoURL); URL url = new URL(latestVersionInfoURL); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { latestVersion = str; } } catch (Exception ex) { LOGGER.error("Error fetching latest version info from: " + latestVersionInfoURL, ex); } finally { try { in.close(); } catch (Exception ex) { LOGGER.error("Could not close inputstream", ex); } } return latestVersion; } Code Sample 2: private LSInput resolveResource(String aPublicId, String aSystemId, String aBaseURI, boolean baseUsed) { LSInput lsInput = new DefaultLSInput(); lsInput.setPublicId(aPublicId); lsInput.setSystemId(aSystemId); String base = null; try { int baseEndPos = -1; if (aBaseURI != null) { baseEndPos = aBaseURI.lastIndexOf("/"); } if (baseEndPos <= 0) { if (baseUsed) { return null; } else { return resolveResource(aPublicId, aSystemId, schemaBasePath + "/" + aSystemId, true); } } base = aBaseURI.substring(0, baseEndPos); URL url = new URL(base + "/" + aSystemId); lsInput.setByteStream(url.openConnection().getInputStream()); return lsInput; } catch (IOException e) { return resolveResource(aPublicId, aSystemId, base, baseUsed); } }