label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void setFinishedFlag(String ip, String port, String user, String dbname, String password, int flag) throws Exception { String sql = "update flag set flag = " + flag; Connection conn = CubridDBCenter.getConnection(ip, port, dbname, user, password); System.out.println("====:::===" + ip); Statement stmt = null; try { conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); conn.commit(); } catch (Exception ex) { ex.printStackTrace(); conn.rollback(); throw ex; } finally { stmt.close(); conn.close(); } } Code Sample 2: public ProgramProfilingMessageSymbol deleteProfilingMessageSymbol(int id) throws AdaptationException { ProgramProfilingMessageSymbol profilingMessageSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program profiling message " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingMessageSymbol = getProfilingMessageSymbol(resultSet); query = "DELETE FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProfilingMessageSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return profilingMessageSymbol; }
00
Code Sample 1: public boolean consolidateCrossrefGet(BiblioItem bib, ArrayList<BiblioItem> bib2) throws Exception { boolean result = false; String doi = bib.getDOI(); String aut = bib.getFirstAuthorSurname(); String title = bib.getTitle(); String firstPage = null; String pageRange = bib.getPageRange(); int beginPage = bib.getBeginPage(); if (beginPage != -1) { firstPage = "" + beginPage; } else if (pageRange != null) { StringTokenizer st = new StringTokenizer(pageRange, "--"); if (st.countTokens() == 2) { firstPage = st.nextToken(); } else if (st.countTokens() == 1) firstPage = pageRange; } if (aut != null) { aut = TextUtilities.removeAccents(aut); } if (title != null) { title = TextUtilities.removeAccents(title); } if (doi != null) { if (doi.startsWith("doi:") | doi.startsWith("DOI:")) { doi.substring(4, doi.length()); doi = doi.trim(); } doi = doi.replace(" ", ""); String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL3); pstmt.setString(1, doi); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF CACHE"); throw new GROBIDServiceException("EXCEPTION HANDLING CROSSREF CACHE.", se); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { String subpath = String.format(DOI_BASE_QUERY, crossref_id, crossref_pw, doi); URL url = new URL("http://" + crossref_host + "/" + subpath); System.out.println("Sending: " + url.toString()); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { urlConn = null; throw new GROBIDServiceException("An exception occured while running Grobid.", e2); } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, " + "but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL3); pstmt2.setString(1, doi); pstmt2.setString(2, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } else if ((title != null) & (aut != null)) { String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL); pstmt.setString(1, aut); pstmt.setString(2, title); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { throw new GROBIDServiceException("EXCEPTION HANDLING CROSSREF CACHE", se); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { String subpath = String.format(TITLE_BASE_QUERY, crossref_id, crossref_pw, URLEncoder.encode(title), URLEncoder.encode(aut)); URL url = new URL("http://" + crossref_host + "/" + subpath); System.out.println("Sending: " + url.toString()); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { urlConn = null; throw new GROBIDServiceException("An exception occured while running Grobid.", e2); } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, " + "but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL); pstmt2.setString(1, aut); pstmt2.setString(2, bib.getTitle()); pstmt2.setString(3, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } else if ((firstPage != null) & (bib.getJournal() != null) & (bib.getVolume() != null)) { String subpath = String.format(JOURNAL_BASE_QUERY, crossref_id, crossref_pw, URLEncoder.encode(bib.getJournal()), URLEncoder.encode(bib.getVolume()), firstPage); URL url = new URL("http://" + crossref_host + "/" + subpath); String urlmsg = url.toString(); System.out.println(urlmsg); String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL2); pstmt.setString(1, urlmsg); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF CACHE"); throw new GROBIDServiceException("EXCEPTION HANDLING CROSSREF CACHE.", se); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { System.out.println("Sending: " + urlmsg); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { urlConn = null; throw new GROBIDServiceException("An exception occured while running Grobid.", e2); } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser p = spf.newSAXParser(); p.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } in.close(); urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, " + "but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL2); pstmt2.setString(1, urlmsg); pstmt2.setString(2, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } return result; } Code Sample 2: protected void givenTestRepository(String repositoryId) throws Exception { HttpResponse response = executeDeleteWithResponse("/repositories/" + repositoryId); consume(response.getEntity()); response = executePost("/repositories", createRepositoryXml(repositoryId)); assertEquals(content(response), SC_CREATED, statusCode(response)); }
00
Code Sample 1: public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); 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(); } } Code Sample 2: public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); }
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: @Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); }
11
Code Sample 1: private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); } Code Sample 2: public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
11
Code Sample 1: private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); } Code Sample 2: @Override public void objectToEntry(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); } }
00
Code Sample 1: public static void main(String[] args) throws IOException { String urltext = "http://www.vogella.de"; URL url = new URL(urltext); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
11
Code Sample 1: private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } } Code Sample 2: private static boolean genMovieRatingFile(String completePath, String masterFile, String CustLocationsFileName, String MovieRatingFileName) { try { File inFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC1 = new FileInputStream(inFile1).getChannel(); int fileSize1 = (int) inC1.size(); int totalNoDataRows = fileSize1 / 7; ByteBuffer mappedBuffer = inC1.map(FileChannel.MapMode.READ_ONLY, 0, fileSize1); System.out.println("Loaded master binary file"); File inFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel inC2 = new FileInputStream(inFile2).getChannel(); int fileSize2 = (int) inC2.size(); System.out.println(fileSize2); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieRatingFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); for (int i = 0; i < 1; i++) { ByteBuffer locBuffer = inC2.map(FileChannel.MapMode.READ_ONLY, i * fileSize2, fileSize2); System.out.println("Loaded cust location file chunk: " + i); while (locBuffer.hasRemaining()) { int locationToRead = locBuffer.getInt(); mappedBuffer.position((locationToRead - 1) * 7); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); ByteBuffer outBuf = ByteBuffer.allocate(3); outBuf.putShort(movieName); outBuf.put(rating); outBuf.flip(); outC.write(outBuf); } } mappedBuffer.clear(); inC1.close(); inC2.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
00
Code Sample 1: public void checkAndDownload(String statsUrl, RDFStatsUpdatableModelExt stats, Date lastDownload, boolean onlyIfNewer) throws DataSourceMonitorException { if (log.isInfoEnabled()) log.info("Checking if update required for statistics of " + ds + "..."); HttpURLConnection urlConnection; try { URL url = new URL(statsUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(READ_TIMEOUT); int statusCode = urlConnection.getResponseCode(); if (statusCode / 100 != 2) { String msg = urlConnection.getResponseMessage(); throw new DataSourceMonitorException(statsUrl + " returned HTTP " + statusCode + (msg != null ? msg : "") + "."); } } catch (Exception e) { throw new DataSourceMonitorException("Failed to connect to " + statsUrl + ".", e); } long lastModified = urlConnection.getLastModified(); boolean newer = lastDownload == null || lastModified == 0 || lastModified - TIMING_GAP > lastDownload.getTime(); if (newer || !onlyIfNewer) { Model newStats = retrieveModelData(urlConnection, ds); Date retrievedTimestamp = Calendar.getInstance().getTime(); Date modifiedTimestamp = (urlConnection.getLastModified() > 0) ? new Date(urlConnection.getLastModified()) : null; if (log.isInfoEnabled()) log.info("Attempt to import up-to-date " + ((modifiedTimestamp != null) ? "(from " + modifiedTimestamp + ") " : "") + "statistics for " + ds + "."); try { if (stats.updateFrom(RDFStatsModelFactory.create(newStats), onlyIfNewer)) stats.setLastDownload(ds.getSPARQLEndpointURL(), retrievedTimestamp); } catch (Exception e) { throw new DataSourceMonitorException("Failed to import statistics and set last download for " + ds + ".", e); } } else { if (log.isInfoEnabled()) log.info("Statistics for " + ds + " are up-to-date" + ((lastDownload != null) ? " (" + lastDownload + ")" : "")); } } Code Sample 2: private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
11
Code Sample 1: public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { LogUtil.d(TAG, "Copying file %s to %s", src, dst); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dst).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { closeSafe(inChannel); closeSafe(outChannel); } }
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 decompress(final File file, final File folder, final boolean deleteZipAfter) throws IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file.getCanonicalFile()))); ZipEntry ze; try { while (null != (ze = zis.getNextEntry())) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (f.exists()) f.delete(); if (ze.isDirectory()) { f.mkdirs(); continue; } f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) fos.write(buf, 0, bytesRead); } finally { fos.close(); } } catch (final IOException ioe) { f.delete(); throw ioe; } } } finally { zis.close(); } if (deleteZipAfter) file.delete(); }
11
Code Sample 1: public FileReader(String filePath, Configuration aConfiguration) throws IOException { file = new File(URLDecoder.decode(filePath, "UTF-8")).getCanonicalFile(); readerConf = aConfiguration; if (file.isDirectory()) { File indexFile = new File(file, "index.php"); File indexFile_1 = new File(file, "index.html"); if (indexFile.exists() && !indexFile.isDirectory()) { file = indexFile; } else if (indexFile_1.exists() && !indexFile_1.isDirectory()) { file = indexFile_1; } else { if (!readerConf.getOption("showFolders").equals("Yes")) { makeErrorPage(503, "Permision denied"); } else { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); File[] files = file.listFiles(); makeHeader(200, -1, new Date(System.currentTimeMillis()).toString(), "text/html"); String title = "Index of " + file; out.write(("<html><head><title>" + title + "</title></head><body><h3>Index of " + file + "</h3><p>\n").getBytes()); for (int i = 0; i < files.length; i++) { file = files[i]; String filename = file.getName(); String description = ""; if (file.isDirectory()) { description = "&lt;DIR&gt;"; } out.write(("<a href=\"" + file.getPath().substring(readerConf.getOption("wwwPath").length()) + "\">" + filename + "</a> " + description + "<br>\n").getBytes()); } out.write(("</p><hr><p>yawwwserwer</p></body><html>").getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } } } else if (!file.exists()) { makeErrorPage(404, "File Not Found."); } else if (getExtension() == ".exe" || getExtension().contains(".py")) { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); out.write((runCommand(filePath)).getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } else { System.out.println(getExtension()); makeHeader(200, file.length(), new Date(file.lastModified()).toString(), TYPES.get(getExtension()).toString()); } System.out.println(file); } Code Sample 2: public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
00
Code Sample 1: @Override public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { String userAgentGroup = processUserAgent(request); final LiwenxRequest lRequest = new LiwenxRequestImpl(request, response, messageSource, userAgentGroup); Locator loc = router.route(lRequest); if (loc instanceof RedirectLocator) { response.sendRedirect(((RedirectLocator) loc).getPage()); } else { ((AbstractLiwenxRequest) lRequest).setRequestedLocator(loc); try { LiwenxResponse resp = processPage(lRequest, lRequest.getRequestedLocator(), maxRedirections); processHeaders(resp, response); processCookies(resp, response); if (resp instanceof ExternalRedirectionResponse) { response.sendRedirect(((ExternalRedirectionResponse) resp).getRedirectTo()); } else if (resp instanceof BinaryResponse) { BinaryResponse bResp = (BinaryResponse) resp; response.setContentType(bResp.getMimeType().toString()); IOUtils.copy(bResp.getInputStream(), response.getOutputStream()); } else if (resp instanceof XmlResponse) { final Element root = ((XmlResponse) resp).getXml(); Document doc = root.getDocument(); if (doc == null) { doc = new Document(root); } final Locator l = lRequest.getCurrentLocator(); final Device device = l.getDevice(); response.setContentType(calculateContentType(device)); response.setCharacterEncoding(encoding); if (device == Device.HTML) { view.processView(doc, l.getLocale(), userAgentGroup, response.getWriter()); } else { Serializer s = new Serializer(response.getOutputStream(), encoding); s.write(doc); } } } catch (PageNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (TooManyRedirectionsException e) { throw e; } catch (Exception e) { throw e; } } } Code Sample 2: public static void loginLetitbit() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to letitbit.com"); HttpPost httppost = new HttpPost("http://letitbit.net/"); httppost.setHeader("Cookie", phpsessioncookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("act", "login")); formparams.add(new BasicNameValuePair("login", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("log")) { logcookie = "log=" + escookie.getValue(); System.out.println(logcookie); } if (escookie.getName().equalsIgnoreCase("pas")) { pascookie = "pas=" + escookie.getValue(); System.out.println(pascookie); } if (escookie.getName().equalsIgnoreCase("host")) { hostcookie = "host=" + escookie.getValue(); System.out.println(hostcookie); } } }
11
Code Sample 1: 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++) { System.out.println("iteration: " + 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); } Code Sample 2: public void testPreparedStatement0009() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0009 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(); } pstmt.close(); assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); con.commit(); pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); rowsToAdd = 6; 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.commit(); pstmt.close(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, rowsToAdd); con.commit(); stmt.close(); con.setAutoCommit(true); }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException(); String inFileName = args[0]; String outFileName = args[1]; File fInput = new File(inFileName); Scanner in = null; try { in = new Scanner(fInput); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(outFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } while (in.hasNextLine()) { out.println(in.nextLine()); } in.close(); out.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
00
Code Sample 1: private String readDataFromUrl(URL url) throws IOException { InputStream inputStream = null; InputStreamReader streamReader = null; BufferedReader in = null; StringBuffer data = new StringBuffer(); try { inputStream = url.openStream(); streamReader = new InputStreamReader(inputStream); in = new BufferedReader(streamReader); String inputLine; while ((inputLine = in.readLine()) != null) data.append(inputLine); } finally { if (in != null) { in.close(); } if (streamReader != null) { streamReader.close(); } if (inputStream != null) { inputStream.close(); } } return data.toString(); } Code Sample 2: public static String getMD5(String s) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(s.getBytes()); byte[] result = md5.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < result.length; i++) { hexString.append(String.format("%02x", 0xFF & result[i])); } return hexString.toString(); }
11
Code Sample 1: public static String toMD5(String seed) { MessageDigest md5 = null; StringBuffer temp_sb = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(seed.getBytes()); byte[] array = md5.digest(); temp_sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x10) temp_sb.append('0'); temp_sb.append(Integer.toHexString(b)); } } catch (NoSuchAlgorithmException err) { err.printStackTrace(); } return temp_sb.toString(); } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the SHA-1 MessageDigest. " + "Jive will be unable to function normally."); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: public DataSet guessAtUnknowns(String filename) { TasselFileType guess = TasselFileType.Sequence; DataSet tds = null; try { BufferedReader br = null; if (filename.startsWith("http")) { URL url = new URL(filename); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { br = new BufferedReader(new FileReader(filename)); } String line1 = br.readLine().trim(); String[] sval1 = line1.split("\\s"); String line2 = br.readLine().trim(); String[] sval2 = line2.split("\\s"); boolean lociMatchNumber = false; if (!sval1[0].startsWith("<") && (sval1.length == 2) && (line1.indexOf(':') < 0)) { int countLoci = Integer.parseInt(sval1[1]); if (countLoci == sval2.length) { lociMatchNumber = true; } } if (sval1[0].equalsIgnoreCase("<Annotated>")) { guess = TasselFileType.Annotated; } else if (line1.startsWith("<") || line1.startsWith("#")) { boolean isTrait = false; boolean isMarker = false; boolean isNumeric = false; boolean isMap = false; Pattern tagPattern = Pattern.compile("[<>\\s]+"); String[] info1 = tagPattern.split(line1); String[] info2 = tagPattern.split(line2); if (info1.length > 1) { if (info1[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info1[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info1[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info1[1].toUpperCase().startsWith("MAP")) { isMap = true; } } if (info2.length > 1) { if (info2[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info2[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info2[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info2[1].toUpperCase().startsWith("MAP")) { isMap = true; } } else { guess = null; String inline = br.readLine(); while (guess == null && inline != null && (inline.startsWith("#") || inline.startsWith("<"))) { if (inline.startsWith("<")) { String[] info = tagPattern.split(inline); if (info[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info[1].toUpperCase().startsWith("MAP")) { isMap = true; } } } } if (isTrait || (isMarker && isNumeric)) { guess = TasselFileType.Phenotype; } else if (isMarker) { guess = TasselFileType.Polymorphism; } else if (isMap) { guess = TasselFileType.GeneticMap; } else { throw new IOException("Improperly formatted header. Data will not be imported."); } } else if ((line1.startsWith(">")) || (line1.startsWith(";"))) { guess = TasselFileType.Fasta; } else if (sval1.length == 1) { guess = TasselFileType.SqrMatrix; } else if (line1.indexOf(':') > 0) { guess = TasselFileType.Polymorphism; } else if ((sval1.length == 2) && (lociMatchNumber)) { guess = TasselFileType.Polymorphism; } else if ((line1.startsWith("#Nexus")) || (line1.startsWith("#NEXUS")) || (line1.startsWith("CLUSTAL")) || ((sval1.length == 2) && (sval2.length == 2))) { guess = TasselFileType.Sequence; } else if (sval1.length == 3) { guess = TasselFileType.Numerical; } myLogger.info("guessAtUnknowns: type: " + guess); tds = processDatum(filename, guess); br.close(); } catch (Exception e) { } return tds; } Code Sample 2: String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
11
Code Sample 1: public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } Code Sample 2: public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
11
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
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 updateDb(int scriptNumber) throws SQLException, IOException { String pathName = updatesPackage.replace(".", "/"); InputStream in = getClass().getClassLoader().getResourceAsStream(pathName + "/" + scriptNumber + ".sql"); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String script = out.toString("UTF-8"); String[] statements = script.split(";"); for (String statement : statements) { getJdbcTemplate().execute(statement); } }
11
Code Sample 1: public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: @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; }
11
Code Sample 1: public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static void main(String[] args) throws IOException { FileChannel fc = new FileOutputStream("src/com/aaron/nio/data.txt").getChannel(); fc.write(ByteBuffer.wrap("dfsdf ".getBytes())); fc.close(); fc = new RandomAccessFile("src/com/aaron/nio/data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("中文的 ".getBytes())); fc.close(); fc = new FileInputStream("src/com/aaron/nio/data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(1024); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { System.out.print(buff.getChar()); } fc.close(); } Code Sample 2: public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/record/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Record Deleted!"); } else { response.setDone(false); response.setMessage("Delete Record Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
00
Code Sample 1: @Override public void onClick(View v) { Log.d(Config.SS_TAG, "Sending POST request to server..."); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Config.RPC_SERVLET_URL); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try { JSONObject callJson = new JSONObject(); callJson.put("method", "ping"); callJson.put("void", "null"); callsJson.put(0, callJson); requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { Log.d(Config.SS_TAG, "Successful ping - status code: " + responseStatusCode); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); JSONObject result = resultsJson.getJSONObject(0); String returnValue = result.getJSONObject("data").getString("return"); Log.d(Config.SS_TAG, "Response message: " + returnValue); } else { Log.e(Config.SS_TAG, "Unsuccessful ping..."); } } catch (Exception e) { Log.e(Config.SS_TAG, "Error while trying to ping rpc servlet"); e.printStackTrace(); } } Code Sample 2: public static String getMD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public String buscaSAIKU() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("SAIKU")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")) { miLinea = inputLine; log.debug(miLinea); miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build SAIKU: " + miLinea); return miLinea; } Code Sample 2: public Reader create(final URI url) throws IOException { this.url = url; if (!url.isAbsolute()) { return new FileReader(new File(url.toString())); } URLConnection connection = url.toURL().openConnection(); connection.setDoInput(true); final InputStream inputStream = connection.getInputStream(); return new InputStreamReader(inputStream); }
11
Code Sample 1: public static String do_checksum(String data) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); StringBuffer strbuf = new StringBuffer(); md5.update(data.getBytes(), 0, data.length()); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { strbuf.append(toHexString(digest[i])); } return strbuf.toString(); } Code Sample 2: public ClientDTO changePassword(String pMail, String pMdp) { Client vClientBean = null; ClientDTO vClientDTO = null; vClientBean = mClientDao.getClient(pMail); if (vClientBean != null) { MessageDigest vMd5Instance; try { vMd5Instance = MessageDigest.getInstance("MD5"); vMd5Instance.reset(); vMd5Instance.update(pMdp.getBytes()); byte[] vDigest = vMd5Instance.digest(); BigInteger vBigInt = new BigInteger(1, vDigest); String vHashPassword = vBigInt.toString(16); vClientBean.setMdp(vHashPassword); vClientDTO = BeanToDTO.getInstance().createClientDTO(vClientBean); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return vClientDTO; }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
11
Code Sample 1: @SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } } Code Sample 2: public static int fileUpload(long lngFileSize, InputStream inputStream, String strFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); if (lngFileSize > (10 * 1024 * 1024)) { return -1; } InputStream is = null; FileOutputStream fos = null; try { File dir = new File(strFilePath); if (!dir.exists()) dir.mkdirs(); is = inputStream; fos = new FileOutputStream(new File(strFilePath + SEPARATOR + strFileName)); IOUtils.copy(is, fos); } catch (Exception ex) { return -2; } finally { try { fos.close(); is.close(); } catch (Exception ex2) { } } return 0; }
00
Code Sample 1: public boolean crear() { int result = 0; String sql = "insert into torneo" + "(nombreTorneo, ciudad, fechaInicio, fechaFinal, organizador, numeroDivisiones, terminado)" + "values (?, ?, ?, ?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(eltorneo); result = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (result > 0); } Code Sample 2: public void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new ProjectEditPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
11
Code Sample 1: public static void copyToFileAndCloseStreams(InputStream istr, File destFile) throws IOException { OutputStream ostr = null; try { ostr = new FileOutputStream(destFile); IOUtils.copy(istr, ostr); } finally { if (ostr != null) ostr.close(); if (istr != null) istr.close(); } } Code Sample 2: public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
11
Code Sample 1: private void copy(String imgPath, String path) { try { File input = new File(imgPath); File output = new File(path, input.getName()); if (output.exists()) { if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return; } byte[] data = new byte[1024]; FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); int length; while ((length = bis.read(data)) > 0) { bos.write(data, 0, length); bos.flush(); } bos.close(); fis.close(); IJavaProject ijp = VisualSwingPlugin.getCurrentProject(); if (ijp != null) { ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); view.refresh(); view.expandAll(); } } catch (Exception e) { VisualSwingPlugin.getLogger().error(e); } } Code Sample 2: public static void copy(final File src, File dst, final boolean overwrite) throws IOException, IllegalArgumentException { if (!src.isFile() || !src.exists()) { throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); } if (dst.exists()) { if (dst.isDirectory()) { dst = new File(dst, src.getName()); } else if (dst.isFile()) { if (!overwrite) { throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); } } else { throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); } } final File dstParent = dst.getParentFile(); if (!dstParent.exists()) { if (!dstParent.mkdirs()) { throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); } } long fileSize = src.length(); if (fileSize > 20971520l) { final FileInputStream in = new FileInputStream(src); final FileOutputStream out = new FileOutputStream(dst); try { int doneCnt = -1; final int bufSize = 32768; final byte buf[] = new byte[bufSize]; while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) { if (doneCnt == 0) { Thread.yield(); } else { out.write(buf, 0, doneCnt); } } out.flush(); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } } } else { final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } } } }
00
Code Sample 1: public void update() { new Thread(new Runnable() { @Override public void run() { try { jButton1.setEnabled(false); jButton2.setEnabled(false); URL url = new URL(updatePath + "currentVersion.txt"); URLConnection con = url.openConnection(); con.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; for (int i = 0; (line = in.readLine()) != null; i++) { URL fileUrl = new URL(updatePath + line); URLConnection filecon = fileUrl.openConnection(); InputStream stream = fileUrl.openStream(); int oneChar, count = 0; int size = filecon.getContentLength(); jProgressBar1.setMaximum(size); jProgressBar1.setValue(0); File testFile = new File(line); String build = ""; for (String dirtest : line.split("/")) { build += dirtest; if (!build.contains(".")) { File dirfile = new File(build); if (!dirfile.exists()) { dirfile.mkdir(); } } build += "/"; } if (testFile.length() == size) { } else { transferFile(line, fileUrl, size); if (line.endsWith("documents.zip")) { ZipInputStream in2 = new ZipInputStream(new FileInputStream(line)); ZipEntry entry; String pathDoc = line.split("documents.zip")[0]; File docDir = new File(pathDoc + "documents"); if (!docDir.exists()) { docDir.mkdir(); } while ((entry = in2.getNextEntry()) != null) { String outFilename = pathDoc + "documents/" + entry.getName(); OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } in2.close(); } if (line.endsWith("mysql.zip")) { ZipFile zipfile = new ZipFile(line); Enumeration entries = zipfile.entries(); String pathDoc = line.split("mysql.zip")[0]; File docDir = new File(pathDoc + "mysql"); if (!docDir.exists()) { docDir.mkdir(); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(pathDoc + "mysql/" + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); InputStream in2 = zipfile.getInputStream(entry); OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName())); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } in2.close(); out.close(); } } } jProgressBar2.setValue(i + 1); labelFileProgress.setText((i + 1) + "/" + numberFiles); } labelStatus.setText("Update Finished"); jButton1.setVisible(false); jButton2.setText("Finished"); jButton1.setEnabled(true); jButton2.setEnabled(true); } catch (IOException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
00
Code Sample 1: public ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt) throws VetoException { if (key == null || fields == null) throw new VetoException("MD5Filter not configured"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getKey()); int[] f = getFields(m); for (int i = 0; i < f.length; i++) { int fld = f[i]; if (m.hasField(fld)) { ISOComponent c = m.getComponent(fld); if (c instanceof ISOBinaryField) md.update((byte[]) c.getValue()); else md.update(((String) c.getValue()).getBytes()); } } byte[] digest = md.digest(); if (m.getDirection() == ISOMsg.OUTGOING) { m.set(new ISOBinaryField(64, digest, 0, 8)); m.set(new ISOBinaryField(128, digest, 8, 8)); } else { byte[] rxDigest = new byte[16]; if (m.hasField(64)) System.arraycopy((byte[]) m.getValue(64), 0, rxDigest, 0, 8); if (m.hasField(128)) System.arraycopy((byte[]) m.getValue(128), 0, rxDigest, 8, 8); if (!Arrays.equals(digest, rxDigest)) { evt.addMessage(m); evt.addMessage("MAC expected: " + ISOUtil.hexString(digest)); evt.addMessage("MAC received: " + ISOUtil.hexString(rxDigest)); throw new VetoException("invalid MAC"); } m.unset(64); m.unset(128); } } catch (NoSuchAlgorithmException e) { throw new VetoException(e); } catch (ISOException e) { throw new VetoException(e); } return m; } Code Sample 2: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; } Code Sample 2: public String getChallengers() { InputStream is = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return "none"; } else return result; } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return "none"; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public boolean updateCalculatedHand(CalculateTransferObject query, BasicStartingHandTransferObject[] hands) throws CalculateDAOException { boolean retval = false; Connection connection = null; Statement statement = null; PreparedStatement prep = null; ResultSet result = null; StringBuffer sql = new StringBuffer(SELECT_ID_SQL); sql.append(appendQuery(query)); try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); statement = connection.createStatement(); result = statement.executeQuery(sql.toString()); if (result.first()) { String id = result.getString("id"); prep = connection.prepareStatement(UPDATE_HANDS_SQL); for (int i = 0; i < hands.length; i++) { prep.setInt(1, hands[i].getWins()); prep.setInt(2, hands[i].getLoses()); prep.setInt(3, hands[i].getDraws()); prep.setString(4, id); prep.setString(5, hands[i].getHand()); if (prep.executeUpdate() != 1) { throw new SQLException("updated too many records in calculatehands, " + id + "-" + hands[i].getHand()); } } connection.commit(); } } catch (SQLException sqle) { try { connection.rollback(); } catch (SQLException e) { e.setNextException(sqle); throw new CalculateDAOException(e); } throw new CalculateDAOException(sqle); } finally { if (result != null) { try { result.close(); } catch (SQLException e) { throw new CalculateDAOException(e); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { throw new CalculateDAOException(e); } } if (prep != null) { try { prep.close(); } catch (SQLException e) { throw new CalculateDAOException(e); } } } return retval; } Code Sample 2: public void removeRoom(int thisRoom) { DBConnection con = null; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String query = "DELETE FROM cafe_Chat_Category WHERE cafe_Chat_Category_id=? "; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); query = "DELETE FROM cafe_Chatroom WHERE cafe_chatroom_category=? "; ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); con.commit(); con.setAutoCommit(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException sqle) { } } finally { if (con != null) con.release(); } }
00
Code Sample 1: private void getLines(PackageManager pm) throws PackageManagerException { final Pattern p = Pattern.compile("\\s*deb\\s+(ftp://|http://)(\\S+)\\s+((\\S+\\s*)*)(./){0,1}"); Matcher m; if (updateUrlAndFile == null) updateUrlAndFile = new ArrayList<UrlAndFile>(); BufferedReader f; String protocol; String host; String shares; String adress; try { f = new BufferedReader(new FileReader(sourcesList)); while ((protocol = f.readLine()) != null) { m = p.matcher(protocol); if (m.matches()) { protocol = m.group(1); host = m.group(2); if (m.group(3).trim().equalsIgnoreCase("./")) shares = ""; else shares = m.group(3).trim(); if (shares == null) adress = protocol + host; else { shares = shares.replace(" ", "/"); if (!host.endsWith("/") && !shares.startsWith("/")) host = host + "/"; adress = host + shares; while (adress.contains("//")) adress = adress.replace("//", "/"); adress = protocol + adress; } if (!adress.endsWith("/")) adress = adress + "/"; String changelogdir = adress; changelogdir = changelogdir.substring(changelogdir.indexOf("//") + 2); if (changelogdir.endsWith("/")) changelogdir = changelogdir.substring(0, changelogdir.lastIndexOf("/")); changelogdir = changelogdir.replace('/', '_'); changelogdir = changelogdir.replaceAll("\\.", "_"); changelogdir = changelogdir.replaceAll("-", "_"); changelogdir = changelogdir.replaceAll(":", "_COLON_"); adress = adress + "Packages.gz"; final String serverFileLocation = adress.replaceAll(":", "_COLON_"); final NameFileLocation nfl = new NameFileLocation(); try { final GZIPInputStream in = new GZIPInputStream(new ConnectToServer(pm).getInputStream(adress)); final String rename = new File(nfl.rename(serverFileLocation, listsDir)).getCanonicalPath(); final FileOutputStream out = new FileOutputStream(rename); final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); final File file = new File(rename); final UrlAndFile uaf = new UrlAndFile(protocol + host, file, changelogdir); updateUrlAndFile.add(uaf); } catch (final Exception e) { final String message = "URL: " + adress + " caused exception"; if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } } f.close(); } catch (final FileNotFoundException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("sourcesList.corrupt", "Entry not found sourcesList.corrupt"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } catch (final IOException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("SearchForServerFile.getLines.IOException", "Entry not found SearchForServerFile.getLines.IOException"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } Code Sample 2: public static String uploadArticleMedia(String localPath, String articleImageName, String year, String month, String day, DataStore db, HttpSession session) { CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); if (!localPath.endsWith(File.separator)) { localPath += File.separator; } FTPClient ftp = new FTPClient(); String liveFTPLogin = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN"); String liveFTPPassword = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD"); String liveImagesServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER"); String liveImagesFolder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER"); if (!liveImagesFolder.endsWith("/")) { liveImagesFolder = liveImagesFolder + "/"; } String liveImagesYearFolder = ""; String liveImagesMonthFolder = ""; String fileLocation = ""; fileLocation += "/" + year + "/" + month + "/" + day; liveImagesYearFolder = liveImagesFolder + year; liveImagesMonthFolder = (liveImagesYearFolder + "/" + month); liveImagesFolder = (liveImagesMonthFolder + "/" + day); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesServer: " + liveImagesServer); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesFolder: " + liveImagesFolder); boolean stored = false; ArrayList servers = splitServers(liveImagesServer); for (int count = 0; count < servers.size(); count++) { String server = (String) servers.get(count); try { int reply; ftp.connect(server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia connecting to server : " + server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + ftp.getReplyString()); CofaxToolsUtil.log(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP uploadArticleMedia ERROR: FTP server refused connection."); } else { ftp.login(liveFTPLogin, liveFTPPassword); } try { ftp.setFileType(FTP.IMAGE_FILE_TYPE); InputStream input; CofaxToolsUtil.log("CofaxToolsFTP: opening file stream: " + localPath + articleImageName); input = new FileInputStream(localPath + articleImageName); CofaxToolsUtil.log("CofaxToolsFTP: attempting to change working directory to: " + liveImagesFolder); boolean changed = ftp.changeWorkingDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + changed); if (changed == false) { CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia attempting to create directory :" + liveImagesFolder); boolean newDirYear = ftp.makeDirectory(liveImagesYearFolder); boolean newDirMonth = ftp.makeDirectory(liveImagesMonthFolder); boolean newDir = ftp.makeDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: YearDir: " + newDirYear + " MonthDir: " + newDirMonth + " finalDir: " + newDir); changed = ftp.changeWorkingDirectory(liveImagesFolder); } if (changed) { CofaxToolsUtil.log("CofaxToolsFTP: storing " + articleImageName + " to " + liveImagesFolder); stored = ftp.storeFile(articleImageName, input); } else { CofaxToolsUtil.log("CofaxToolsFTP: failed changing: " + liveImagesFolder); } if (stored) { CofaxToolsUtil.log("CofaxToolsFTP: Successfully ftped file."); } else { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file."); } input.close(); ftp.logout(); ftp.disconnect(); } catch (org.apache.commons.net.io.CopyStreamException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); CofaxToolsUtil.log("CofaxToolsFTP: " + e.getIOException().toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (IOException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (Exception e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } } catch (IOException e) { return ("Could not connect to server: " + e); } } return (""); }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); try { URL url = new URL("http://placekitten.com/g/500/250"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500); Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); output.eraseColor(Color.BLACK); Canvas canvas = new Canvas(output); canvas.drawBitmap(kitten, 125, 125, new Paint()); canvas.drawBitmap(frame, 0, 0, new Paint()); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); textPaint.setTextAlign(Align.CENTER); textPaint.setAntiAlias(true); textPaint.setTextSize(36); canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint); textPaint.setTextSize(24); canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint); ImageView imageView = (ImageView) this.findViewById(R.id.imageView); imageView.setImageBitmap(output); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
11
Code Sample 1: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: public byte[] read(IFile input) { InputStream contents = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); contents = input.getContents(); IOUtils.copy(contents, baos); return baos.toByteArray(); } catch (IOException e) { Activator.logUnexpected(null, e); } catch (CoreException e) { Activator.logUnexpected(null, e); } finally { IOUtils.closeQuietly(contents); } return null; }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); }
00
Code Sample 1: public static void redirect(String strRequest, PrintWriter sortie) throws Exception { String level = "info."; if (ConnectorServlet.debug) level = "debug."; Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.GFI"); URL url2Request = new URL(strRequest); URLConnection conn = url2Request.openConnection(); DataInputStream buffin = new DataInputStream(new BufferedInputStream(conn.getInputStream())); String strLine = null; while ((strLine = buffin.readLine()) != null) { sortie.println(strLine); } buffin.close(); } Code Sample 2: private void fillTemplate(String resource, OutputStream outputStream, Map<String, String> replacements) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { for (String key : replacements.keySet()) { String value = replacements.get(key); if (key != null) { line = line.replace(key, value); } } writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); }
00
Code Sample 1: public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } Code Sample 2: public void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } button.setEnabled(true); }
11
Code Sample 1: public String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static String encrypt(String password) { String sign = password; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(sign.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } sign = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return sign; }
11
Code Sample 1: public void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } }
11
Code Sample 1: public static String sendSoapMsg(String SOAPUrl, byte[] b, String SOAPAction) throws IOException { log.finest("HTTP REQUEST SIZE " + b.length); if (SOAPAction.startsWith("\"") == false) SOAPAction = "\"" + SOAPAction + "\""; URL url = new URL(SOAPUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty("Pragma", "no-cache"); 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); StringBuffer response = new StringBuffer(1024); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); log.finest("HTTP RESPONSE SIZE: " + response.length()); return response.toString(); } Code Sample 2: private List<Intrebare> citesteIntrebari() throws IOException { ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>(); try { URL url = new URL(getCodeBase(), "../intrebari.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); String intrebare; while ((intrebare = reader.readLine()) != null) { Collection<String> raspunsuri = new ArrayList<String>(); Collection<String> predicate = new ArrayList<String>(); String raspuns = ""; while (!"".equals(raspuns = reader.readLine())) { raspunsuri.add(raspuns); predicate.add(reader.readLine()); } Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()])); intrebari.add(i); } } catch (ArgumentExcetpion e) { e.printStackTrace(); } return intrebari; }
00
Code Sample 1: private static String saveCookie(String username, String password) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); URL url = new URL("https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("login=" + username + "&password=" + password); out.flush(); String cookie = conn.getHeaderField("Set-Cookie"); cookie = cookie.substring(0, cookie.indexOf(";")); out.close(); conn.disconnect(); return cookie; } catch (Exception e) { return ""; } } Code Sample 2: public static void main(String[] args) { FileInputStream in; DeflaterOutputStream out; FileOutputStream fos; FileDialog fd; fd = new FileDialog(new Frame(), "Find a file to deflate", FileDialog.LOAD); fd.show(); if (fd.getFile() != null) { try { in = new FileInputStream(new File(fd.getDirectory(), fd.getFile())); fos = new FileOutputStream(new File("Deflated.out")); out = new DeflaterOutputStream(fos, new Deflater(Deflater.DEFLATED, true)); int bytes_read = 0; byte[] buffer = new byte[1024]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } fos.flush(); fos.close(); out.flush(); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } 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 static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] raw = mDigest.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(raw); } Code Sample 2: @Override public boolean identification(String username, String password) { this.getLogger().info(DbUserServiceImpl.class, ">>>identification " + username + "<<<"); try { IFeelerUser user = this.getDbServ().queryFeelerUser(username); if (user == null) { return false; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); if (user.getPassword().equals(new String(md5.digest()))) { if (!this.localUUIDList.contains(user.getUuid())) { this.localUUIDList.add(user.getUuid()); } return true; } else { return false; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); } Code Sample 2: void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: private static void generateFile(String inputFilename, String outputFilename) throws Exception { File inputFile = new File(inputFilename); if (inputFile.exists() == false) { throw new Exception(Messages.getString("ScriptDocToBinary.Input_File_Does_Not_Exist") + inputFilename); } Environment environment = new Environment(); environment.initBuiltInObjects(); NativeObjectsReader reader = new NativeObjectsReader(environment); InputStream input = new FileInputStream(inputFile); System.out.println(Messages.getString("ScriptDocToBinary.Reading_Documentation") + inputFilename); reader.loadXML(input); checkFile(outputFilename); File binaryFile = new File(outputFilename); FileOutputStream outputStream = new FileOutputStream(binaryFile); TabledOutputStream output = new TabledOutputStream(outputStream); reader.getScriptDoc().write(output); output.close(); System.out.println(Messages.getString("ScriptDocToBinary.Finished")); System.out.println(); } Code Sample 2: @Override public void copierPhotos(FileInputStream fichierACopier, FileOutputStream fichierDestination) { FileChannel in = null; FileChannel out = null; try { in = fichierACopier.getChannel(); out = fichierDestination.getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public static void main(String[] args) { if (args.length < 1) { System.out.println("Parameters: method arg1 arg2 arg3 etc"); System.out.println(""); System.out.println("Methods:"); System.out.println(" reloadpolicies"); System.out.println(" migratedatastreamcontrolgroup"); System.exit(0); } String method = args[0].toLowerCase(); if (method.equals("reloadpolicies")) { if (args.length == 4) { try { reloadPolicies(args[1], args[2], args[3]); System.out.println("SUCCESS: Policies have been reloaded"); System.exit(0); } catch (Throwable th) { th.printStackTrace(); System.err.println("ERROR: Reloading policies failed; see above"); System.exit(1); } } else { System.err.println("ERROR: Three arguments required: " + "http|https username password"); System.exit(1); } } else if (method.equals("migratedatastreamcontrolgroup")) { if (args.length > 10) { System.err.println("ERROR: too many arguments provided"); System.exit(1); } if (args.length < 7) { System.err.println("ERROR: insufficient arguments provided. Arguments are: "); System.err.println(" protocol [http|https]"); System.err.println(" user"); System.err.println(" password"); System.err.println(" pid - either"); System.err.println(" a single pid, eg demo:object"); System.err.println(" list of pids separated by commas, eg demo:object1,demo:object2"); System.err.println(" name of file containing pids, eg file:///path/to/file"); System.err.println(" dsid - either"); System.err.println(" a single datastream id, eg DC"); System.err.println(" list of ids separated by commas, eg DC,RELS-EXT"); System.err.println(" controlGroup - target control group (note only M is implemented)"); System.err.println(" addXMLHeader - add an XML header to the datastream [true|false, default false]"); System.err.println(" reformat - reformat the XML [true|false, default false]"); System.err.println(" setMIMETypeCharset - add charset=UTF-8 to the MIMEType [true|false, default false]"); System.exit(1); } try { boolean addXMLHeader = getArgBoolean(args, 7, false); boolean reformat = getArgBoolean(args, 8, false); boolean setMIMETypeCharset = getArgBoolean(args, 9, false); ; InputStream is = modifyDatastreamControlGroup(args[1], args[2], args[3], args[4], args[5], args[6], addXMLHeader, reformat, setMIMETypeCharset); IOUtils.copy(is, System.out); is.close(); System.out.println("SUCCESS: Datastreams modified"); System.exit(0); } catch (Throwable th) { th.printStackTrace(); System.err.println("ERROR: migrating datastream control group failed; see above"); System.exit(1); } } else { System.err.println("ERROR: unrecognised method " + method); System.exit(1); } } Code Sample 2: public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException { FileOutputStream fileOut; File file; ZipEntry zipEntry; ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder); while ((zipEntry = zipIn.getNextEntry()) != null) { file = new File(outputDirectory + File.separator + zipEntry.getName()); if (zipEntry.isDirectory()) { createDirectory(file.getPath(), ""); } else { File parent = file.getParentFile(); if (!parent.exists()) { createDirectory(parent.getPath(), ""); } fileOut = new FileOutputStream(file); int readedBytes; while ((readedBytes = zipIn.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); } zipIn.closeEntry(); } }
11
Code Sample 1: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { 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: public static void decompress(File apps,File f) throws IOException{ String filename=f.getName(); filename=filename.substring(0,filename.length()-PACK_FILE_SUFFIX.length()); File dir=new File(apps,filename); if(!dir.exists()){ dir.mkdirs(); } if(dir.isDirectory()){ JarFile jar=new JarFile(f); Enumeration<JarEntry> files=jar.entries(); while(files.hasMoreElements()){ JarEntry je=files.nextElement(); if(je.isDirectory()){ File item=new File(dir,je.getName()); item.mkdirs(); }else{ File item=new File(dir,je.getName()); item.getParentFile().mkdirs(); InputStream input=jar.getInputStream(je); FileOutputStream out=new FileOutputStream(item); IOUtils.copy(input, out); input.close(); out.close(); } //System.out.println(je.isDirectory() + je.getName()); } } }
11
Code Sample 1: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } } Code Sample 2: public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
00
Code Sample 1: public synchronized void connect() throws FTPException, IOException { if (eventAggregator != null) { eventAggregator.setConnId(ftpClient.getId()); ftpClient.setMessageListener(eventAggregator); ftpClient.setProgressMonitor(eventAggregator); ftpClient.setProgressMonitorEx(eventAggregator); } statistics.clear(); configureClient(); log.debug("Configured client"); ftpClient.connect(); log.debug("Client connected"); if (masterContext.isAutoLogin()) { log.debug("Logging in"); ftpClient.login(masterContext.getUserName(), masterContext.getPassword()); log.debug("Logged in"); configureTransferType(masterContext.getContentType()); } else { log.debug("Manual login enabled"); } } Code Sample 2: public void render(HttpServletRequest request, HttpServletResponse response, File file, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } if (file.length() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Cannot send file greater than 2GB"); } response.setContentLength((int) file.length()); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); }
00
Code Sample 1: public static void setFinishedFlag(String ip, String port, String user, String dbname, String password, int flag) throws Exception { String sql = "update flag set flag = " + flag; Connection conn = CubridDBCenter.getConnection(ip, port, dbname, user, password); System.out.println("====:::===" + ip); Statement stmt = null; try { conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); conn.commit(); } catch (Exception ex) { ex.printStackTrace(); conn.rollback(); throw ex; } finally { stmt.close(); conn.close(); } } Code Sample 2: public static String getMD5(String text) { if (text == null) { return null; } String result = null; try { MessageDigest md5 = MessageDigest.getInstance(ALG_MD5); md5.update(text.getBytes(ENCODING)); result = "" + new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
00
Code Sample 1: public static String executePost(String urlStr, Map paramsMap) throws IOException { StringBuffer result = new StringBuffer(); HttpURLConnection connection = null; URL url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); Iterator paramKeys = paramsMap.keySet().iterator(); while (paramKeys.hasNext()) { String paramName = (String) paramKeys.next(); out.print(paramName + "=" + paramsMap.get(paramName)); if (paramKeys.hasNext()) { out.print('&'); } } out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); String msg = result.toString(); return stripOuterElement(msg); } Code Sample 2: public static boolean downloadRegPage() { String filename = "register.php?csz=" + checkEmptyString(jDtr) + "&&mac=" + MAC + "&&uname=" + checkEmptyString(InstallName) + "&&cname=" + checkEmptyString(InstallCompany) + "&&winuname=" + checkEmptyString(WinName) + "&&wincname=" + checkEmptyString(WinCompany) + "&&age=" + checkEmptyString(jAge) + "&&sal=" + checkEmptyString(jSal) + "&&sta=" + checkEmptyString(jSta) + "&&sex=" + checkEmptyString(jSex) + "&&con=" + checkEmptyString(jCon) + "&&occ=" + checkEmptyString(jOcc) + "&&int=" + checkEmptyString(jInt) + "&&ver=" + checkEmptyString(jVer) + "&&mor=" + checkEmptyString(jTyp); URL url1 = null; try { url1 = new URL(url + filename); } catch (MalformedURLException e1) { } int status = 0; try { status = ((HttpURLConnection) url1.openConnection()).getResponseCode(); } catch (IOException e1) { System.out.println(e1); } if (status == 200) { return true; } else { return false; } }
00
Code Sample 1: private void pushResource(String peerId, String communityId, String resourceFilePath, List<String> attachmentFilePaths) throws IOException { String urlString = "http://" + peerId + "/upload"; HttpURLConnection uploadConnection = null; DataOutputStream connOutput = null; FileInputStream fileInput = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "232404jkg4220957934FW"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { File resourceFile = new File(resourceFilePath); if (!resourceFile.exists()) { LOG.error("JTellaAdapter: Resource file could not be found for push: " + resourceFilePath); return; } List<File> attachments = new ArrayList<File>(); for (String attachmentPath : attachmentFilePaths) { File attachFile = new File(attachmentPath); if (!attachFile.exists()) { LOG.error("JTellaAdapter: Attachment file could not be found for push: " + attachmentPath); return; } attachments.add(attachFile); } LOG.debug("JTellaAdapter: Initiating push to: " + urlString); URL url = new URL(urlString); uploadConnection = (HttpURLConnection) url.openConnection(); uploadConnection.setDoInput(true); uploadConnection.setDoOutput(true); uploadConnection.setUseCaches(false); uploadConnection.setRequestMethod("POST"); uploadConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); uploadConnection.setRequestProperty("Connection", "Keep-Alive"); uploadConnection.setRequestProperty("User-Agent", "UP2P"); uploadConnection.setRequestProperty("Accept", "[star]/[star]"); connOutput = new DataOutputStream(uploadConnection.getOutputStream()); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:community\"" + lineEnd + lineEnd); connOutput.writeBytes(communityId + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:pushupload\"" + lineEnd + lineEnd + "true" + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); boolean fileWriteComplete = false; boolean resourceFileWritten = false; File nextFile = null; while (!fileWriteComplete) { if (!resourceFileWritten) { nextFile = resourceFile; } else { nextFile = attachments.remove(0); } LOG.debug("JTellaAdapter: PUSHing file: " + nextFile.getAbsolutePath()); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:filename\";" + " filename=\"" + nextFile.getName() + "\"" + lineEnd); connOutput.writeBytes(lineEnd); fileInput = new FileInputStream(nextFile); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInput.read(buffer, 0, bufferSize); while (bytesRead > 0) { connOutput.write(buffer, 0, bufferSize); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInput.read(buffer, 0, bufferSize); } connOutput.writeBytes(lineEnd); if (attachments.isEmpty()) { connOutput.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); } else { connOutput.writeBytes(twoHyphens + boundary + lineEnd); } resourceFileWritten = true; if (attachments.isEmpty()) { fileWriteComplete = true; } } BufferedReader inStream = new BufferedReader(new InputStreamReader(uploadConnection.getInputStream())); while (inStream.readLine() != null) ; inStream.close(); LOG.debug("JTellaAdapter: Push upload was succesful."); } catch (MalformedURLException ex) { LOG.error("JTellaAdapter: pushResource Malformed URL: " + ex); throw new IOException("pushResource failed for URL: " + urlString); } catch (IOException ioe) { LOG.error("JTellaAdapter: pushResource IOException: " + ioe); throw new IOException("pushResource failed for URL: " + urlString); } finally { try { if (fileInput != null) { fileInput.close(); } if (connOutput != null) { connOutput.flush(); } if (connOutput != null) { connOutput.close(); } if (uploadConnection != null) { uploadConnection.disconnect(); } } catch (IOException e) { LOG.error("JTellaAdapter: pushResource failed to close connection streams."); } } } Code Sample 2: public static boolean verify(final String password, final String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } final byte[] data = Base64.decode(base64.toCharArray()); final byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
00
Code Sample 1: @Override public List<String> getNamedEntitites(String sentence) { List<String> namedEntities = new ArrayList<String>(); try { URL url = new URL(SERVICE_URL + "text=" + URLEncoder.encode(sentence, "UTF-8") + "&confidence=" + CONFIDENCE + "&support=" + SUPPORT); URLConnection conn = url.openConnection(); conn.setRequestProperty("accept", "application/json"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); JSONObject json = new JSONObject(sb.toString()); if (!json.isNull("Resources")) { JSONArray array = json.getJSONArray("Resources"); JSONObject entityObject; for (int i = 0; i < array.length(); i++) { entityObject = array.getJSONObject(i); System.out.println("Entity: " + entityObject.getString("@surfaceForm")); System.out.println("DBpedia URI: " + entityObject.getString("@URI")); System.out.println("Types: " + entityObject.getString("@types")); namedEntities.add(entityObject.getString("@surfaceForm")); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return namedEntities; } Code Sample 2: public static void copyTo(File src, File dest) throws IOException { if (src.equals(dest)) throw new IOException("copyTo src==dest file"); FileOutputStream fout = new FileOutputStream(dest); InputStream in = new FileInputStream(src); IOUtils.copyTo(in, fout); fout.flush(); fout.close(); in.close(); }
11
Code Sample 1: public void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = 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: private String grabInformationFromWeb(String query, String infoName) throws Exception { String result = ""; URL url = new URL(query); HttpURLConnection request = null; request = (HttpURLConnection) url.openConnection(); if (request != null) { InputStream in = url.openStream(); int c = 0; StringBuilder sb = new StringBuilder(); while ((c = in.read()) != -1) { sb = sb.append((char) c); } String s = sb.toString(); result = Utils.getTagValue(s, "<" + infoName + ">", "</" + infoName + ">"); in.close(); } return result; } Code Sample 2: private void saveScore(int score) { String name = JOptionPane.showInputDialog(this, "Skriv navn for å komme på highscorelisten!", "Lagre score!", JOptionPane.INFORMATION_MESSAGE); URL url; try { url = new URL("http://129.177.17.51:8080/GuestBook/TheOnlyServlet?name=" + name + "&score=" + score); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); urlConnection.getInputStream(); BrowserControl.openUrl("http://129.177.17.51:8080/GuestBook/TheOnlyServlet"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } return hexString.toString(); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: @SuppressWarnings("unchecked") public void handle(Map<String, Object> data, String urlPath) { try { URL url = new URL(urlPath); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; CMGroup currentGroup = null; List<CMGroup> groups = (List<CMGroup>) data.get(CMConstants.GROUP); List<CMTag> tags = (List<CMTag>) data.get(CMConstants.TAG); List<CMTagGroup> tagGroups = (List<CMTagGroup>) data.get(CMConstants.TAG_GROUP); while ((line = reader.readLine()) != null) { CMGroup group = null; try { group = FetchUtil.getCMGroup(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMGroup error:" + line); } if (group != null) { if (currentGroup != null) { groups.add(currentGroup); } currentGroup = group; } CMTag tag = null; try { tag = FetchUtil.getCMTag(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMTag error:" + line); } if (tag != null) { CMTagGroup tagGroup = new CMTagGroup(); tagGroup.setGroupName(currentGroup.getName()); tagGroup.setTagName(tag.getName()); tags.add(tag); tagGroups.add(tagGroup); } } groups.add(currentGroup); reader.close(); } catch (MalformedURLException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } catch (IOException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } } Code Sample 2: private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } Code Sample 2: public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
11
Code Sample 1: public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options) throws Exception { log.debug("Determining zip file organization..."); BosVisitor visitor = new DxpFileOrganizingBosVisitor(); visitor.visit(mapBos); if (!options.isQuiet()) log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"..."); OutputStream outStream = new FileOutputStream(outputZipFile); ZipOutputStream zipOutStream = new ZipOutputStream(outStream); ZipEntry entry = null; URI rootMapUri = mapBos.getRoot().getEffectiveUri(); URI baseUri = null; try { baseUri = AddressingUtil.getParent(rootMapUri); } catch (URISyntaxException e) { throw new BosException("URI syntax exception getting parent URI: " + e.getMessage()); } Set<String> dirs = new HashSet<String>(); if (!options.isQuiet()) log.info("Constructing DXP package..."); for (BosMember member : mapBos.getMembers()) { if (!options.isQuiet()) log.info("Adding member " + member + " to zip..."); URI relativeUri = baseUri.relativize(member.getEffectiveUri()); File temp = new File(relativeUri.getPath()); String parentPath = temp.getParent(); if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) { parentPath += "/"; } log.debug("parentPath=\"" + parentPath + "\""); if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) { entry = new ZipEntry(parentPath); zipOutStream.putNextEntry(entry); zipOutStream.closeEntry(); dirs.add(parentPath); } entry = new ZipEntry(relativeUri.getPath()); zipOutStream.putNextEntry(entry); IOUtils.copy(member.getInputStream(), zipOutStream); zipOutStream.closeEntry(); } zipOutStream.close(); if (!options.isQuiet()) log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created."); } Code Sample 2: public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: 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(); } } Code Sample 2: void run(String[] args) { InputStream istream = System.in; System.out.println("TradeMaximizer " + version); String filename = parseArgs(args, false); if (filename != null) { System.out.println("Input from: " + filename); try { if (filename.startsWith("http:") || filename.startsWith("ftp:")) { URL url = new URL(filename); istream = url.openStream(); } else istream = new FileInputStream(filename); } catch (IOException ex) { fatalError(ex.toString()); } } List<String[]> wantLists = readWantLists(istream); if (wantLists == null) return; if (options.size() > 0) { System.out.print("Options:"); for (String option : options) System.out.print(" " + option); System.out.println(); } System.out.println(); try { MessageDigest digest = MessageDigest.getInstance("MD5"); for (String[] wset : wantLists) { for (String w : wset) { digest.update((byte) ' '); digest.update(w.getBytes()); } digest.update((byte) '\n'); } System.out.println("Input Checksum: " + toHexString(digest.digest())); } catch (NoSuchAlgorithmException ex) { } parseArgs(args, true); if (iterations > 1 && seed == -1) { seed = System.currentTimeMillis(); System.out.println("No explicit SEED, using " + seed); } if (!(metric instanceof MetricSumSquares) && priorityScheme != NO_PRIORITIES) System.out.println("Warning: using priorities with the non-default metric is normally worthless"); buildGraph(wantLists); if (showMissing && officialNames != null && officialNames.size() > 0) { for (String name : usedNames) officialNames.remove(name); List<String> missing = new ArrayList<String>(officialNames); Collections.sort(missing); for (String name : missing) { System.out.println("**** Missing want list for official name " + name); } System.out.println(); } if (showErrors && errors.size() > 0) { Collections.sort(errors); System.out.println("ERRORS:"); for (String error : errors) System.out.println(error); System.out.println(); } long startTime = System.currentTimeMillis(); graph.removeImpossibleEdges(); List<List<Graph.Vertex>> bestCycles = graph.findCycles(); int bestMetric = metric.calculate(bestCycles); if (iterations > 1) { System.out.println(metric); graph.saveMatches(); for (int i = 0; i < iterations - 1; i++) { graph.shuffle(); List<List<Graph.Vertex>> cycles = graph.findCycles(); int newMetric = metric.calculate(cycles); if (newMetric < bestMetric) { bestMetric = newMetric; bestCycles = cycles; graph.saveMatches(); System.out.println(metric); } else if (verbose) System.out.println("# " + metric); } System.out.println(); graph.restoreMatches(); } long stopTime = System.currentTimeMillis(); displayMatches(bestCycles); if (showElapsedTime) System.out.println("Elapsed time = " + (stopTime - startTime) + "ms"); }
11
Code Sample 1: private void storeFieldMap(Content c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (java.util.Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } } Code Sample 2: private String addEqError(EquivalencyException e, int namespaceId) throws SQLException { List l = Arrays.asList(e.getListOfEqErrors()); int size = l.size(); String sql = getClassifyDAO().getStatement(TABLE_KEY, "ADD_CLASSIFY_EQ_ERROR"); PreparedStatement ps = null; conn.setAutoCommit(false); try { deleteCycleError(namespaceId); deleteEqError(namespaceId); long conceptGID1 = -1; long conceptGID2 = -1; ps = conn.prepareStatement(sql); for (int i = 0; i < l.size(); i++) { EqError error = (EqError) l.get(i); ConceptRef ref1 = error.getConcept1(); ConceptRef ref2 = error.getConcept2(); conceptGID1 = getConceptGID(ref1, namespaceId); conceptGID2 = getConceptGID(ref2, namespaceId); ps.setLong(1, conceptGID1); ps.setLong(2, conceptGID2); ps.setInt(3, namespaceId); int result = ps.executeUpdate(); if (result == 0) { throw new SQLException("unable to add eq error: " + sql); } } conn.commit(); return "EquivalencyException: Concept: " + conceptGID1 + " namespaceId: " + namespaceId + " conceptGID2: " + conceptGID2 + ((size > 1) ? "...... more" : ""); } catch (SQLException sqle) { conn.rollback(); throw sqle; } catch (Exception ex) { conn.rollback(); throw toSQLException(ex, "cannot add eq errors"); } finally { conn.setAutoCommit(true); if (ps != null) { ps.close(); } } }
11
Code Sample 1: public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: @Deprecated public static void getAndProcessContents(String videoPageURL, int bufsize, String charset, Closure<String> process) throws IOException { URL url = null; HttpURLConnection connection = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { url = new URL(videoPageURL); connection = (HttpURLConnection) url.openConnection(); is = connection.getInputStream(); isr = new InputStreamReader(is, charset); br = new BufferedReader(isr); for (String line = br.readLine(); line != null; line = br.readLine()) { process.exec(line); } } finally { Closeables.closeQuietly(br); Closeables.closeQuietly(isr); Closeables.closeQuietly(is); HttpUtils.disconnect(connection); } } Code Sample 2: public IUserProfile getUserProfile(String profileID) throws MM4UUserProfileNotFoundException { SimpleUserProfile tempProfile = null; String tempProfileString = this.profileURI + profileID + FILE_SUFFIX; try { URL url = new URL(tempProfileString); Debug.println("Retrieve profile with ID: " + url); tempProfile = new SimpleUserProfile(); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String tempLine = null; tempProfile.add("id", profileID); while ((tempLine = input.readLine()) != null) { Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine); if (tempProperty != null) { tempProfile.addIfNotNull(tempProperty.getKey(), tempProperty.getValue()); } } input.close(); } catch (MalformedURLException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } catch (IOException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } return tempProfile; }
11
Code Sample 1: private String unzip(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } } Code Sample 2: @Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } }
11
Code Sample 1: public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } } Code Sample 2: public String openFileAsText(String resource) throws IOException { StringWriter wtr = new StringWriter(); InputStreamReader rdr = new InputStreamReader(openFile(resource)); try { IOUtils.copy(rdr, wtr); } finally { IOUtils.closeQuietly(rdr); } return wtr.toString(); }
00
Code Sample 1: public void setUrl(URL url) throws PDFException, PDFSecurityException, IOException { InputStream in = null; try { URLConnection urlConnection = url.openConnection(); in = urlConnection.getInputStream(); String pathOrURL = url.toString(); setInputStream(in, pathOrURL); } finally { if (in != null) { in.close(); } } } Code Sample 2: public static String getURLContent(String urlPath, String charset) { BufferedReader reader = null; HttpURLConnection conn = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(urlPath); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setUseCaches(false); conn.setDefaultUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(60000); conn.connect(); int repCode = conn.getResponseCode(); if (repCode == 200) { int count = 0; char[] chBuffer = new char[1024]; BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); while ((count = input.read(chBuffer)) != -1) { buffer.append(chBuffer, 0, count); } } } catch (Exception ex) { logger.error("", ex); } finally { try { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception ex) { } } return buffer.toString(); }
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 static void main(String[] args) throws IOException { File fileIn = new File("D:\\zz_c\\study2\\src\\study\\io\\A.java"); InputStream fin = new FileInputStream(fileIn); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(); pout.connect(pin); IoRead i = new IoRead(); i.setIn(pin); File fileOU1 = new File("D:\\zz_c\\study2\\src\\study\\io\\A1.java"); File fileOU2 = new File("D:\\zz_c\\study2\\src\\study\\io\\A2.java"); File fileOU3 = new File("D:\\zz_c\\study2\\src\\study\\io\\A3.java"); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU1))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU2))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU3))); PipedInputStream pin2 = new PipedInputStream(); PipedOutputStream pout2 = new PipedOutputStream(); i.addOut(pout2); pout2.connect(pin2); i.start(); int read; try { read = fin.read(); while (read != -1) { pout.write(read); read = fin.read(); } fin.close(); pout.close(); } catch (IOException e) { e.printStackTrace(); } int c = pin2.read(); while (c != -1) { System.out.print((char) c); c = pin2.read(); } pin2.close(); }
00
Code Sample 1: @Override protected InputStream getResourceStream(String name) throws Exception { final BundleEntry entry = cpm.findLocalEntry(name); if (entry != null) return entry.getInputStream(); final URL url = cpm.getBaseData().getBundle().getResource(name); if (url != null) return url.openStream(); return null; } Code Sample 2: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String pluginPathInfo = pathInfo.substring(prefix.length()); String gwtPathInfo = pluginPathInfo.substring(pluginKey.length() + 1); String clPath = CLASSPATH_PREFIX + gwtPathInfo; InputStream input = cl.getResourceAsStream(clPath); if (input != null) { try { OutputStream output = resp.getOutputStream(); IOUtils.copy(input, output); } finally { input.close(); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void actionPerformed(ActionEvent ae) { String actionCommand = ae.getActionCommand(); if (actionCommand == null) { return; } if (DataManager.SHOW_DEBUG) { System.out.println("Action command : " + actionCommand); } DataManager dataManager = ClientDirector.getDataManager(); PlayerImpl myPlayer = dataManager.getMyPlayer(); if (!myPlayer.getLocation().isRoom() && actionCommand.equals("createChatRoom")) { JOptionPane.showMessageDialog(null, "Sorry, but you can not create/leave chat channels\n" + "on World/Town Maps.", "INFORMATION", JOptionPane.INFORMATION_MESSAGE); return; } if (actionCommand.equals("createChatRoom")) { WotlasLocation chatRoomLocation = myPlayer.getLocation(); String chatRoomName = JOptionPane.showInputDialog("Please enter a Name:"); if (chatRoomName == null || chatRoomName.length() == 0) { return; } if (this.tabbedPane.getTabCount() >= ChatRoom.MAXIMUM_CHATROOMS_PER_ROOM - 1) { this.b_createChatRoom.setEnabled(false); } else { this.b_createChatRoom.setEnabled(true); } myPlayer.sendMessage(new ChatRoomCreationMessage(chatRoomName, myPlayer.getPrimaryKey())); } else if (actionCommand.equals("leaveChatRoom")) { if (!this.currentPrimaryKey.equals(ChatRoom.DEFAULT_CHAT)) { myPlayer.sendMessage(new RemPlayerFromChatRoomMessage(myPlayer.getPrimaryKey(), this.currentPrimaryKey)); } } else if (actionCommand.equals("helpChat")) { DataManager dManager = ClientDirector.getDataManager(); dManager.sendMessage(new SendTextMessage(dManager.getMyPlayer().getPrimaryKey(), dManager.getMyPlayer().getPlayerName(), getMyCurrentChatPrimaryKey(), "/help", ChatRoom.NORMAL_VOICE_LEVEL)); } else if (actionCommand.equals("imageChat")) { String imageURL = JOptionPane.showInputDialog("Please enter your image's URL:\nExample: http://wotlas.sf.net/images/wotlas.gif"); if (imageURL == null || imageURL.length() == 0) { return; } try { URL url = new URL(imageURL); URLConnection urlC = url.openConnection(); urlC.connect(); String ctype = urlC.getContentType(); if (!ctype.startsWith("image/")) { JOptionPane.showMessageDialog(null, "The specified URL does not refer to an image !", "Information", JOptionPane.INFORMATION_MESSAGE); return; } if (urlC.getContentLength() > 50 * 1024) { JOptionPane.showMessageDialog(null, "The specified image is too big (above 50kB).", "Information", JOptionPane.INFORMATION_MESSAGE); return; } } catch (Exception ex) { Debug.signal(Debug.ERROR, this, "Failed to get image: " + ex); JOptionPane.showMessageDialog(null, "Failed to get the specified image...\nCheck your URL.", "Error", JOptionPane.ERROR_MESSAGE); return; } DataManager dManager = ClientDirector.getDataManager(); dManager.sendMessage(new SendTextMessage(dManager.getMyPlayer().getPrimaryKey(), dManager.getMyPlayer().getPlayerName(), getMyCurrentChatPrimaryKey(), "<img src='" + imageURL + "'>", ChatRoom.NORMAL_VOICE_LEVEL)); } else { if (DataManager.SHOW_DEBUG) { System.out.println("Err : unknown actionCommand"); System.out.println("No action command found!"); } } } Code Sample 2: public static String getHash(String text) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); ret = getHex(md.digest()); } catch (NoSuchAlgorithmException e) { log.error(e); throw new OopsException(e, "Hash Error."); } return ret; }
11
Code Sample 1: 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 expected = getClass().getResourceAsStream(CONTENT_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(); } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); } Code Sample 2: public void actionPerformed(ActionEvent ev) { if (fileChooser == null) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)"); fileFilter.addExtension("jar"); fileFilter.addExtension("zip"); fileChooser.setFileFilter(fileFilter); } if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) { String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); JarFile jar = null; try { jar = new JarFile(fileChooser.getSelectedFile()); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } urls[0] = fileChooser.getSelectedFile().toURL(); } catch (IOException e) { Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e); return; } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { String entryName = (String) it.next(); try { devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class)); } catch (IOException e) { Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e); return; } } for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) en.nextElement(); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), fileChooser.getSelectedFile().getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(fileChooser.getSelectedFile(), deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } lsDevicesModel.addElement(entry); Config.addDeviceEntry(entry); } lsDevices.setSelectedValue(entry, true); } catch (IOException e) { Message.error("Error adding device profile, " + Message.getCauseMessage(e), e); return; } } }
00
Code Sample 1: public static void main(String[] args) throws Exception { for (int n = 0; n < 8; n++) { new Thread() { public void run() { try { URL url = new URL("http://localhost:8080/WebGISTileServer/index.jsp?token_timeout=true"); URLConnection uc = url.openConnection(); uc.addRequestProperty("Referer", "http://localhost:8080/index.jsp"); BufferedReader rd = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while ((line = rd.readLine()) != null) System.out.println(line); } catch (Exception e) { e.printStackTrace(); } } }.start(); } } Code Sample 2: private void saveFile(InputStream in, String fullPath) { try { File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(in, out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public boolean finish() { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName.getText()); try { project.create(null); project.open(null); IProjectDescription desc = project.getDescription(); desc.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(desc, null); IJavaProject javaProject = JavaCore.create(project); IPath fitLib = project.getFullPath().append(FIT_LIBRARY); javaProject.setRawClasspath(createClassPathEntries(project, fitLib), null); copyLibrary(project); javaProject.setOutputLocation(createOutputFolder(project, DEFAULT_OUTPUT_FOLDER).getFullPath(), null); createOutputFolder(project, fitTests.getText()); createOutputFolder(project, fitResults.getText()); if (!DEFAULT_OUTPUT_FOLDER.equals(fitResults.getText())) { DefaultFolderProperties.setDefinedOutputLocation(project, fitResults.getText()); } if (!DEFAULT_SOURCE_FOLDER.equals(fitFixtures.getText())) { DefaultFolderProperties.setDefinedSourceLocation(project, fitFixtures.getText()); } if (includeExamplesCheck.getSelection()) { copySamples(project); } } catch (CoreException e) { handleError(getContainer().getShell(), project, "Could not create project:" + e.getMessage()); return false; } catch (IOException e) { handleError(getContainer().getShell(), project, "Could not create project:" + e.getMessage()); return false; } return true; } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: protected Object insertSingle(Object name, Object fact) throws SQLException { DFAgentDescription dfd = (DFAgentDescription) fact; AID agentAID = dfd.getName(); String agentName = agentAID.getName(); DFAgentDescription dfdToReturn = null; String batchErrMsg = ""; Connection conn = getConnectionWrapper().getConnection(); PreparedStatements pss = getPreparedStatements(); try { dfdToReturn = (DFAgentDescription) removeSingle(dfd.getName()); Date leaseTime = dfd.getLeaseTime(); long lt = (leaseTime != null ? leaseTime.getTime() : -1); String descrId = getGUID(); pss.stm_insAgentDescr.setString(1, descrId); pss.stm_insAgentDescr.setString(2, agentName); pss.stm_insAgentDescr.setString(3, String.valueOf(lt)); pss.stm_insAgentDescr.executeUpdate(); saveAID(agentAID); Iterator iter = dfd.getAllLanguages(); if (iter.hasNext()) { pss.stm_insLanguage.clearBatch(); while (iter.hasNext()) { pss.stm_insLanguage.setString(1, descrId); pss.stm_insLanguage.setString(2, (String) iter.next()); pss.stm_insLanguage.addBatch(); } pss.stm_insLanguage.executeBatch(); } iter = dfd.getAllOntologies(); if (iter.hasNext()) { pss.stm_insOntology.clearBatch(); while (iter.hasNext()) { pss.stm_insOntology.setString(1, descrId); pss.stm_insOntology.setString(2, (String) iter.next()); pss.stm_insOntology.addBatch(); } pss.stm_insOntology.executeBatch(); } iter = dfd.getAllProtocols(); if (iter.hasNext()) { pss.stm_insProtocol.clearBatch(); while (iter.hasNext()) { pss.stm_insProtocol.setString(1, descrId); pss.stm_insProtocol.setString(2, (String) iter.next()); pss.stm_insProtocol.addBatch(); } pss.stm_insProtocol.executeBatch(); } saveServices(descrId, dfd.getAllServices()); regsCnt++; if (regsCnt > MAX_REGISTER_WITHOUT_CLEAN) { regsCnt = 0; clean(); } conn.commit(); } catch (SQLException sqle) { try { conn.rollback(); } catch (SQLException se) { logger.log(Logger.SEVERE, "Rollback for incomplete insertion of DFD for agent " + dfd.getName() + " failed.", se); } throw sqle; } return dfdToReturn; } Code Sample 2: @Override public void backup() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); Date date = new Date(); date.setTime(TimeUtil.addHours(date, -getHours()).getTimeInMillis()); date.setTime(TimeUtil.getTodayAtMidnight().getTimeInMillis()); if (logger.isInfoEnabled()) logger.info("backuping records before: " + date); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + getOrigin() + " where " + getCondition() + ""); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); prestm.setDate(1, sqlDate); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (currentRows > 0) { connection.setAutoCommit(false); prestm = connection.prepareStatement("INSERT INTO " + getDestination() + " SELECT * FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(rows + " rows backupped"); prestm = connection.prepareStatement("DELETE FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); rows = prestm.executeUpdate(); prestm.close(); connection.commit(); if (logger.isInfoEnabled()) logger.info(rows + " rows deleted"); } else if (logger.isInfoEnabled()) logger.info("no backup need"); if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
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: public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private static String fetch(String urltxt, String cookie) { try { URL url = new URL(urltxt); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream source = url.openStream(); String data = new Scanner(source).useDelimiter("\\A").next(); Pattern p = Pattern.compile("form action=\"(.*)\" method=\"post\""); Matcher m = p.matcher(data); if (!m.find()) return ""; urltxt = m.group(1); url = new URL(urltxt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", cookie); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("dl.start=PREMIUM"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); while ((data = in.readLine()) != null) sb.append(data + System.getProperty("line.separator")); data = urltxt.substring(urltxt.lastIndexOf("/") + 1); p = Pattern.compile("<tr><td><a href=\"(.*?)" + data); m = p.matcher(sb.toString()); data = (m.find()) ? (m.group(1) + data + System.getProperty("line.separator")) : ""; return data; } catch (Exception e) { return ""; } } Code Sample 2: private boolean postCorrecao() { boolean valido = false; Integer newCodCorrecao = null; String sqlmaxac = "SELECT MAX(SEQAC) FROM PPOPACAOCORRET WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; String sqlmaxcq = "SELECT MAX(SEQOPCQ) + 1 FROM PPOPCQ WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; try { for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { valido = true; keysItens[2] = ek.getKey(); break; } } if (!valido) { Funcoes.mensagemInforma(this, "Selecione as analises para aplicar a corre��o!"); return false; } if (txaCausa.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Informe as causas!"); return false; } if (txaAcao.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Detalhe a a��o corretiva!"); return false; } PreparedStatement ps = con.prepareStatement(sqlmaxac); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ResultSet rs = ps.executeQuery(); if (rs.next()) { newCodCorrecao = rs.getInt(1) + 1; keysItens[3] = newCodCorrecao; } rs.close(); ps.close(); if (newCodCorrecao != null) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO PPOPACAOCORRET "); sql.append("( CODEMP, CODFILIAL, CODOP, SEQOP, SEQAC, TPCAUSA, OBSCAUSA, TPACAO, OBSACAO ) "); sql.append("VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, newCodCorrecao); ps.setString(6, m.getCode()); ps.setString(7, txaCausa.getVlrString()); ps.setString(8, rgSolucao.getVlrString()); ps.setString(9, txaAcao.getVlrString()); ps.execute(); ps.close(); String strAnalises = ""; for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { if (strAnalises.trim().length() > 0) { strAnalises += ","; } strAnalises += String.valueOf(ek.getKey()); } } sql = new StringBuilder(); sql.append("UPDATE PPOPCQ SET SEQAC=? "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, newCodCorrecao); ps.setInt(2, Aplicativo.iCodEmp); ps.setInt(3, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(4, txtCodOP.getVlrInteger()); ps.setInt(5, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); sql.delete(0, sql.length()); sql.append("INSERT INTO PPOPCQ (CODEMP,CODFILIAL,CODOP,SEQOP,SEQOPCQ,"); sql.append("CODEMPEA,CODFILIALEA,CODESTANALISE) "); sql.append("SELECT CODEMP,CODFILIAL,CODOP,SEQOP,("); sql.append(sqlmaxcq); sql.append("),CODEMPEA,CODFILIALEA,CODESTANALISE "); sql.append("FROM PPOPCQ "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND "); sql.append("SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); System.out.println(sql.toString()); ps = con.prepareStatement(sql.toString()); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(7, txtCodOP.getVlrInteger()); ps.setInt(8, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); montaAnalises(); Funcoes.mensagemInforma(this, "A��o corretiva aplicada com sucesso!"); } con.commit(); } catch (Exception err) { try { con.rollback(); } catch (SQLException e) { System.out.println("Erro ao realizar rollback!\n" + err.getMessage()); } err.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao atualizar analises!\n" + err.getMessage(), true, con, err); valido = false; } return valido; }
11
Code Sample 1: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } Code Sample 2: private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
11
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static final synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally."); nsae.printStackTrace(); } } digest.update(data.getBytes()); return encodeHex(digest.digest()); } Code Sample 2: private static String deviceIdFromCombined_Device_ID(Context context) { StringBuilder builder = new StringBuilder(); builder.append(deviceIdFromIMEI(context)); builder.append(deviceIdFromPseudo_Unique_Id()); builder.append(deviceIdFromAndroidId(context)); builder.append(deviceIdFromWLAN_MAC_Address(context)); builder.append(deviceIdFromBT_MAC_Address(context)); String m_szLongID = builder.toString(); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(m_szLongID.getBytes(), 0, m_szLongID.length()); byte p_md5Data[] = m.digest(); String m_szUniqueID = new String(); for (int i = 0; i < p_md5Data.length; i++) { int b = (0xFF & p_md5Data[i]); if (b <= 0xF) m_szUniqueID += "0"; m_szUniqueID += Integer.toHexString(b); } return m_szUniqueID; }
11
Code Sample 1: public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: public static void copyFile(String src, String target) throws IOException { FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(target).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
00
Code Sample 1: public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); } Code Sample 2: public void ftpUpload() { FTPClient ftpclient = null; InputStream is = null; try { ftpclient = new FTPClient(); ftpclient.connect(host, port); if (logger.isDebugEnabled()) { logger.debug("FTP连接远程服务器:" + host); } ftpclient.login(user, password); if (logger.isDebugEnabled()) { logger.debug("登陆用户:" + user); } ftpclient.setFileType(FTP.BINARY_FILE_TYPE); ftpclient.changeWorkingDirectory(remotePath); is = new FileInputStream(localPath + File.separator + filename); ftpclient.storeFile(filename, is); logger.info("上传文件结束...路径:" + remotePath + ",文件名:" + filename); is.close(); ftpclient.logout(); } catch (IOException e) { logger.error("上传文件失败", e); } finally { if (ftpclient.isConnected()) { try { ftpclient.disconnect(); } catch (IOException e) { logger.error("断开FTP出错", e); } } ftpclient = null; } }
11
Code Sample 1: public static final void parse(String infile, String outfile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(infile)); DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile)); int w = Integer.parseInt(reader.readLine()); int h = Integer.parseInt(reader.readLine()); output.writeByte(w); output.writeByte(h); int lineCount = 2; try { do { for (int i = 0; i < h; i++) { lineCount++; String line = reader.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of file at line " + lineCount); } for (int j = 0; j < w; j++) { char c = line.charAt(j); System.out.print(c); output.writeByte(c); } System.out.println(""); } lineCount++; output.writeShort(Short.parseShort(reader.readLine())); } while (reader.readLine() != null); } finally { reader.close(); output.close(); } } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void copy(File source, File dest) throws IOException { System.out.println("copy " + source + " -> " + dest); FileInputStream in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { out.close(); } } finally { in.close(); } }
11
Code Sample 1: public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); 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().substring(8, 24); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } } Code Sample 2: public String encodePassword(String rawPass, Object salt) { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (java.security.NoSuchAlgorithmException e) { throw new LdapDataAccessException("No SHA implementation available!"); } sha.update(rawPass.getBytes()); if (salt != null) { Assert.isInstanceOf(byte[].class, salt, "Salt value must be a byte array"); sha.update((byte[]) salt); } byte[] hash = combineHashAndSalt(sha.digest(), (byte[]) salt); return (salt == null ? SHA_PREFIX : SSHA_PREFIX) + new String(Base64.encodeBase64(hash)); }
00
Code Sample 1: private void googleImageSearch() { bottomShowing = true; googleSearched = true; googleImageLocation = 0; googleImages = new Vector<String>(); custom = ""; int r = JOptionPane.showConfirmDialog(this, "Customize google search?", "Google Search", JOptionPane.YES_NO_OPTION); if (r == JOptionPane.YES_OPTION) { custom = JOptionPane.showInputDialog("Custom Search", ""); } else { custom = artist; } try { String u = "http://images.google.com/images?q=" + custom; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String lin = new String(); while ((lin = readIn.readLine()) != null) { while (lin.contains("href=\"/imgres?imgurl=")) { while (!lin.contains(">")) { lin += readIn.readLine(); } String s = lin.substring(lin.indexOf("href=\"/imgres?imgurl="), lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); lin = lin.substring(lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); if (s.contains("&amp;") && s.indexOf("http://") < s.indexOf("&amp;")) { s = s.substring(s.indexOf("http://"), s.indexOf("&amp;")); } else { s = s.substring(s.indexOf("http://"), s.length()); } googleImages.add(s); } } readIn.close(); } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton1.setEnabled(false); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); } Code Sample 2: public void xtestFile2() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile2.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
11
Code Sample 1: public void uploadFile(ActionEvent event) throws IOException { InputFile inputFile = (InputFile) event.getSource(); synchronized (inputFile) { ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); String fileNewPath = arrangeUplodedFilePath(context.getRealPath(""), inputFile.getFile().getName()); File file = new File(fileNewPath); System.out.println(fileNewPath); DataInputStream inStream = new DataInputStream(new FileInputStream(inputFile.getFile())); DataOutputStream outStream = new DataOutputStream(new FileOutputStream(file)); int i = 0; byte[] buffer = new byte[512]; while ((i = inStream.read(buffer, 0, 512)) != -1) outStream.write(buffer, 0, i); } } Code Sample 2: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new OutputStream() { @Override public void write(byte[] b, int off, int len) { } @Override public void write(int b) { } @Override public void write(byte[] b) throws IOException { } }); } finally { IOUtils.closeQuietly(in); } return checksum; }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject> \n " + json.toString() + " \n </jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); this.dm.insertIntoClients(tempStringAgent, tempStringClient, tempStringRoute, tempStringZone); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) try { inChannel.close(); } catch (Exception e) { } ; if (outChannel != null) try { outChannel.close(); } catch (Exception e) { } ; } }
00
Code Sample 1: @SuppressWarnings("static-access") public void run() { valuesRow = new String[this.getMaxCounter()]; for (int i = 0; i < this.getMaxCounter(); i++) { InputStream is = null; try { String surl = "http://download.finance.yahoo.com/d/quotes.csv?s=^GDAXI&f=sl1d1t1c1ohgv&e=.csv"; URL url = new URL(surl); is = url.openStream(); BufferedReader dis = new BufferedReader(new InputStreamReader(is)); String s = dis.readLine(); System.out.println(s); valuesRow[i] = s; is.close(); } catch (MalformedURLException mue) { System.out.println("Ouch - a MalformedURLException happened."); mue.printStackTrace(); System.exit(1); } catch (IOException ioe) { System.out.println("Oops- an IOException happened."); ioe.printStackTrace(); System.exit(1); } try { Thread.currentThread().sleep(this.getTsleep()); } catch (InterruptedException e) { } } System.out.println("valuesRow.length=" + valuesRow.length); } Code Sample 2: public File getFile(String file) { DirProperties dp; List files = new ArrayList(); for (int i = 0; i < locs.size(); i++) { dp = (DirProperties) locs.get(i); if (dp.isReadable()) { File g = new File(dp.getLocation() + slash() + file); if (g.exists()) files.add(g); } } if (files.size() == 0) { throw new UnsupportedOperationException("at least one DirProperty should get 'read=true'"); } else if (files.size() == 1) { return (File) files.get(0); } else { File fromFile = (File) files.get(files.size() - 2); File toFile = (File) files.get(files.size() - 1); byte reading[] = new byte[2024]; try { FileInputStream stream = new FileInputStream(fromFile); FileOutputStream outStr = new FileOutputStream(toFile); while (stream.read(reading) != -1) { outStr.write(reading); } } catch (FileNotFoundException ex) { getLogger().severe("FileNotFound: while copying from " + fromFile + " to " + toFile); } catch (IOException ex) { getLogger().severe("IOException: while copying from " + fromFile + " to " + toFile); } return toFile; } }
11
Code Sample 1: public void readEntry(String name, InputStream input) throws Exception { File file = new File(this.directory, name); OutputStream output = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { org.apache.commons.io.IOUtils.copy(input, output); } finally { output.close(); } } Code Sample 2: public static void writeInputStreamToFile(final InputStream stream, final File target) { long size = 0; FileOutputStream fileOut; try { fileOut = new FileOutputStream(target); size = IOUtils.copyLarge(stream, fileOut); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (log.isInfoEnabled()) { log.info("Wrote " + size + " bytes to " + target.getAbsolutePath()); } else { System.out.println("Wrote " + size + " bytes to " + target.getAbsolutePath()); } }
00
Code Sample 1: public void mouseClicked(MouseEvent e) { String userNameString; String passwordString; String md5String = ""; MessageDigest md; userNameString = userNameJTextField.getText(); passwordString = passwordJTextField.getText(); try { md = MessageDigest.getInstance("MD5"); md.update(passwordString.getBytes()); md5String = new String(md.digest()); md5String = Base64.encode(md5String.getBytes()); System.out.println(md5String); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); System.out.println("ʧ��"); } if (userNameString.equals("zouwulingde") && md5String.equals("aKdtP09kSTkWCD/cylk=")) { JOptionPane.showMessageDialog(null, "��ӭʹ��ѧ���ڹ���ϵͳ��"); } else { JOptionPane.showMessageDialog(null, "�û�������벻��ȷ!!!!"); } } Code Sample 2: public static final boolean zipExtract(String zipfile, String name, String dest) { boolean f = false; try { InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); ZipInputStream zin = new ZipInputStream(in); ZipEntry e; while ((e = zin.getNextEntry()) != null) { if (e.getName().equals(name)) { FileOutputStream out = new FileOutputStream(dest); byte b[] = new byte[TEMP_FILE_BUFFER_SIZE]; int len = 0; while ((len = zin.read(b)) != -1) out.write(b, 0, len); out.close(); f = true; break; } } zin.close(); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } return (f); }
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 void run() { try { URL url = new URL("http://mydiversite.appspot.com/version.html"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }