label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: private void extractByParsingHtml(String refererURL, String requestURL) throws MalformedURLException, IOException { URL url = new URL(refererURL); InputStream is = url.openStream(); mRefererURL = refererURL; if (requestURL.startsWith("http://www.")) { mRequestURLWWW = requestURL; mRequestURL = "http://" + mRequestURLWWW.substring(11); } else { mRequestURL = requestURL; mRequestURLWWW = "http://www." + mRequestURL.substring(7); } Parser parser = (new HTMLEditorKit() { public Parser getParser() { return super.getParser(); } }).getParser(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } StringReader sr = new StringReader(sb.toString()); parser.parse(sr, new LinkbackCallback(), true); if (mStart != 0 && mEnd != 0 && mEnd > mStart) { mExcerpt = sb.toString().substring(mStart, mEnd); mExcerpt = Utilities.removeHTML(mExcerpt); if (mExcerpt.length() > mMaxExcerpt) { mExcerpt = mExcerpt.substring(0, mMaxExcerpt) + "..."; } } if (mTitle.startsWith(">") && mTitle.length() > 1) { mTitle = mTitle.substring(1); } } Code Sample 2: public static void gunzip(File gzippedFile, File destinationFile) throws IOException { int buffer = 2048; FileInputStream in = new FileInputStream(gzippedFile); GZIPInputStream zipin = new GZIPInputStream(in); byte[] data = new byte[buffer]; FileOutputStream out = new FileOutputStream(destinationFile); int length; while ((length = zipin.read(data, 0, buffer)) != -1) out.write(data, 0, length); out.close(); zipin.close(); }
00
Code Sample 1: private void getViolationsReportByProductOfferIdYearMonth() throws IOException { String xmlFile8Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonth.xml"; URL url8; url8 = new URL(bmReportingWSUrl); URLConnection connection8 = url8.openConnection(); HttpURLConnection httpConn8 = (HttpURLConnection) connection8; FileInputStream fin8 = new FileInputStream(xmlFile8Send); ByteArrayOutputStream bout8 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin8, bout8); fin8.close(); byte[] b8 = bout8.toByteArray(); httpConn8.setRequestProperty("Content-Length", String.valueOf(b8.length)); httpConn8.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn8.setRequestProperty("SOAPAction", soapAction); httpConn8.setRequestMethod("POST"); httpConn8.setDoOutput(true); httpConn8.setDoInput(true); OutputStream out8 = httpConn8.getOutputStream(); out8.write(b8); out8.close(); InputStreamReader isr8 = new InputStreamReader(httpConn8.getInputStream()); BufferedReader in8 = new BufferedReader(isr8); String inputLine8; StringBuffer response8 = new StringBuffer(); while ((inputLine8 = in8.readLine()) != null) { response8.append(inputLine8); } in8.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name:" + "getViolationsReportByProductOfferIdYearMonth\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response8.toString()); } 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 reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, out); writer.setPdfVersion(PdfWriter.VERSION_1_3); writer.setFullCompression(); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STRENGTH128BITS, password, null, securityType); } final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } else if (base_url != null) { document.addTitle(base_url); } final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator(IHtmlToPdfTransformer.VERSION); } final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.addProducer(sproducer); } else { document.addProducer(IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer); } document.open(); } PdfImportedPage page; for (int j = 0; j < n; ) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } } document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext(); ) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i).replaceAll("<pagecount>", "" + n); final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } else { reader = new PdfReader(tmp2.getAbsolutePath()); } final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STRENGTH128BITS, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } stp.close(); oldOut.flush(); } } catch (final Exception e) { throw new CConvertException("ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } finally { try { tmp.delete(); } catch (final Exception ignore) { } try { tmp2.delete(); } catch (final Exception ignore) { } } } Code Sample 2: public JSONObject getSourceGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph src = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { src = manager.getSourceGraph(); if (src != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(src); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No source graph loaded."); } } catch (Exception e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Cannot load source graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
00
Code Sample 1: public HttpResponse execute(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("Client connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } try { HttpResponse response = doSendRequest(request, conn, context); if (response == null) { response = doReceiveResponse(request, conn, context); } return response; } catch (IOException ex) { conn.close(); throw ex; } catch (HttpException ex) { conn.close(); throw ex; } catch (RuntimeException ex) { conn.close(); throw ex; } } Code Sample 2: 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; }
11
Code Sample 1: private boolean copy_to_file_io(File src, File dst) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); is = new BufferedInputStream(is); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); byte buffer[] = new byte[1024 * 64]; int read; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } return true; } finally { try { if (is != null) is.close(); } catch (IOException e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (IOException e) { Debug.debug(e); } } } Code Sample 2: 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(); }
11
Code Sample 1: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } } Code Sample 2: public static void generateCode(File flowFile, String packagePath, File destDir, File scriptRootFolder) throws IOException { InputStream javaSrcIn = generateCode(flowFile, packagePath, scriptRootFolder); File outputFolder = new File(destDir, packagePath.replace('.', File.separatorChar)); String fileName = flowFile.getName(); fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + Consts.FILE_EXTENSION_GROOVY; File outputFile = new File(outputFolder, fileName); OutputStream javaSrcOut = new FileOutputStream(outputFile); IOUtils.copyBufferedStream(javaSrcIn, javaSrcOut); javaSrcIn.close(); javaSrcOut.close(); }
11
Code Sample 1: public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } } Code Sample 2: public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map _headers, Map _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams params = ((HttpMethodBase) method).getParams(); if (params == null) { params = new HttpMethodParams(); ((HttpMethodBase) method).setParams(params); } if (_timeout < 0) params.setSoTimeout(0); else params.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap(); _headers.put("Content-Type", _contentType); } if (_headers != null) { Iterator iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } InputStream instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); instream.close(); } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } }
11
Code Sample 1: private void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static ByteBuffer join(ByteBuffer buffer1, ByteBuffer buffer2) { if (buffer2 == null || buffer2.remaining() == 0) return NIOUtils.copy(buffer1); if (buffer1 == null || buffer1.remaining() == 0) return NIOUtils.copy(buffer2); ByteBuffer buffer = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining()); buffer.put(buffer1); buffer.put(buffer2); buffer.flip(); return buffer; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static String readJarURL(URL url) throws IOException { JarURLConnection juc = (JarURLConnection) url.openConnection(); InputStream in = juc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { out.write(i); i = in.read(); } return out.toString(); }
11
Code Sample 1: public static void copy(File src, File dest, boolean overwrite) throws IOException { if (!src.exists()) throw new IOException("File source does not exists"); if (dest.exists()) { if (!overwrite) throw new IOException("File destination already exists"); dest.delete(); } else { dest.createNewFile(); } InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dest); byte[] buffer = new byte[1024 * 4]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.close(); is.close(); } Code Sample 2: @Override public void render(Output output) throws IOException { output.setStatus(statusCode, statusMessage); if (headersMap != null) { Iterator<Entry<String, String>> iterator = headersMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> header = iterator.next(); output.addHeader(header.getKey(), header.getValue()); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
11
Code Sample 1: public String encodePassword(String password, byte[] salt) throws Exception { if (salt == null) { salt = new byte[12]; secureRandom.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(salt, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new String(Base64.encode(storedPassword)); } Code Sample 2: public boolean verify(final char[] password, final String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; 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 IllegalStateException("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 IllegalStateException("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 IllegalStateException("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 IllegalStateException("Invalid algorithm"); } } else { return false; } try { final byte[] data = Base64.decodeBase64(base64.getBytes("UTF-8")); final byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(new String(password).getBytes("UTF-8")); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 Unsupported"); } }
11
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; }
00
Code Sample 1: public static void copy(File source, File target) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER); while (in.read(buffer) != -1) { buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } buffer.clear(); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { close(in); close(out); } } Code Sample 2: public static final String MD5(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String newValue = hash.toString(16); return newValue; } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return null; } }
11
Code Sample 1: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: 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(); try { MessageDigest md = MessageDigest.getInstance("MD5"); 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])); } } } catch (NoSuchAlgorithmException e) { throw new ForumException("" + e); } return hexString.toString(); }
00
Code Sample 1: @Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); } Code Sample 2: public static InputStream retrievePricesHTML(String username, String password) throws IOException, SAXException { List<String> cookies = new ArrayList<String>(); URL url = new URL("http://motormouth.com.au/default_fl.aspx"); HttpURLConnection loginConnection = (HttpURLConnection) url.openConnection(); String viewStateValue = HTMLParser.parseHTMLInputTagValue(new InputStreamReader(loginConnection.getInputStream()), "__VIEWSTATE"); setCookies(cookies, loginConnection); HttpURLConnection postCredsConnection = (HttpURLConnection) url.openConnection(); postCredsConnection.setDoOutput(true); postCredsConnection.setRequestMethod("POST"); postCredsConnection.setInstanceFollowRedirects(false); postCredsConnection.setRequestProperty("Cookie", buildCookieString(cookies)); OutputStreamWriter postCredsWriter = new OutputStreamWriter(postCredsConnection.getOutputStream()); postCredsWriter.append("__VIEWSTATE=").append(URLEncoder.encode(viewStateValue, "UTF-8")).append('&'); postCredsWriter.append("Login_Module1%3Ausername=").append(URLEncoder.encode(username, "UTF-8")).append('&'); postCredsWriter.append("Login_Module1%3Apassword=").append(URLEncoder.encode(password, "UTF-8")).append('&'); postCredsWriter.append("Login_Module1%3AButtonLogin.x=0").append('&'); postCredsWriter.append("Login_Module1%3AButtonLogin.y=0"); postCredsWriter.flush(); postCredsWriter.close(); int postResponseCode = postCredsConnection.getResponseCode(); if (postResponseCode == 302) { setCookies(cookies, postCredsConnection); URL dataUrl = new URL(url, postCredsConnection.getHeaderField("Location")); HttpURLConnection dataConnection = (HttpURLConnection) dataUrl.openConnection(); dataConnection.setRequestProperty("Cookie", buildCookieString(cookies)); InputStream dataInputStream = dataConnection.getInputStream(); return dataInputStream; } else if (postResponseCode == 200) { URL dataUrl = new URL(url, "/secure/mymotormouth.aspx"); HttpURLConnection dataConnection = (HttpURLConnection) dataUrl.openConnection(); dataConnection.setRequestProperty("Cookie", buildCookieString(cookies)); InputStream dataInputStream = dataConnection.getInputStream(); return dataInputStream; } else { return null; } }
00
Code Sample 1: public static boolean copyFile(File source, File dest) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } return true; } Code Sample 2: public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); }
00
Code Sample 1: public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; } Code Sample 2: public static void bubbleSort(int[] array) { for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - i - 1; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } System.out.println("��" + (i + 1) + "������"); for (int k = 0; k < array.length; k++) { System.out.print(array[k] + " "); } System.out.println(); } }
00
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 TestReport runImpl() throws Exception { DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parserClassName); File f = (new File(testFileName)); URL url = f.toURL(); Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream()); Element e = doc.getElementById(targetId); if (e == null) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_GET_ELEMENT_BY_ID_FAILED); report.addDescriptionEntry(ENTRY_KEY_ID, targetId); report.setPassed(false); return report; } e.setAttribute(targetAttribute, targetValue); if (targetValue.equals(e.getAttribute(targetAttribute))) { return reportSuccess(); } DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(TestReport.ERROR_TEST_FAILED); report.setPassed(false); return report; }
00
Code Sample 1: public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: private static String doHash(String frase, String algorithm) { try { String ret; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(frase.getBytes()); BigInteger bigInt = new BigInteger(1, md.digest()); ret = bigInt.toString(16); return ret; } catch (NoSuchAlgorithmException e) { return null; } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static int ToGSML(GeoSciML_Mapping mapping, String strTemplate, String strRequest, PrintWriter sortie, String requestedSRS) throws Exception { String level = "info."; if (ConnectorServlet.debug) level = "debug."; Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.Gml2Gsml"); log.debug(strRequest); String tagFeature = "FIELDS"; URL url2Request = new URL(strRequest); URLConnection conn = url2Request.openConnection(); Date dDebut = new Date(); BufferedReader buffin = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strLine = null; int nbFeatures = 0; Template template = VelocityCreator.createTemplate("/fr/brgm/exows/gml2gsml/templates/" + strTemplate); while ((strLine = buffin.readLine()) != null) { if (strLine.indexOf(tagFeature) != -1) { nbFeatures++; GSMLFeatureGeneric feature = createGSMLFeatureFromGMLFeatureString(mapping, strLine); VelocityContext context = new VelocityContext(); context.put("feature", feature); String outputFeatureMember = VelocityCreator.createXMLbyContext(context, template); sortie.println(outputFeatureMember); } } buffin.close(); Date dFin = new Date(); String output = "GEOSCIML : " + nbFeatures + " features handled - time : " + (dFin.getTime() - dDebut.getTime()) / 1000 + " [" + dDebut + " // " + dFin + "]"; log.trace(output); return nbFeatures; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } Code Sample 2: public static void copy(FileInputStream in, File destination) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = in.getChannel(); dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } }
00
Code Sample 1: public static long getLastModified(URL url) throws IOException { if ("file".equals(url.getProtocol())) { String externalForm = url.toExternalForm(); File file = new File(externalForm.substring(5)); return file.lastModified(); } else { URLConnection connection = url.openConnection(); long modified = connection.getLastModified(); try { InputStream is = connection.getInputStream(); if (is != null) is.close(); } catch (UnknownServiceException use) { } catch (IOException ioe) { } return modified; } } Code Sample 2: private void copyLocalFile(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: @Override protected IStatus run(IProgressMonitor monitor) { final int BUFFER_SIZE = 1024; final int DISPLAY_BUFFER_SIZE = 8196; File sourceFile = new File(_sourceFile); File destFile = new File(_destFile); if (sourceFile.exists()) { try { Log.getInstance(FileCopierJob.class).debug(String.format("Start copy of %s to %s", _sourceFile, _destFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); monitor.beginTask(Messages.getString("FileCopierJob.MainTask") + " " + _sourceFile, (int) ((sourceFile.length() / DISPLAY_BUFFER_SIZE) + 4)); monitor.worked(1); byte[] buffer = new byte[BUFFER_SIZE]; int stepRead = 0; int read; boolean copying = true; while (copying) { read = bis.read(buffer); if (read > 0) { bos.write(buffer, 0, read); stepRead += read; } else { copying = false; } if (monitor.isCanceled()) { bos.close(); bis.close(); deleteFile(_destFile); return Status.CANCEL_STATUS; } if (stepRead >= DISPLAY_BUFFER_SIZE) { monitor.worked(1); stepRead = 0; } } bos.flush(); bos.close(); bis.close(); monitor.worked(1); } catch (Exception e) { processError("Error while copying: " + e.getMessage()); } Log.getInstance(FileCopierJob.class).debug("End of copy."); return Status.OK_STATUS; } else { processError(Messages.getString("FileCopierJob.ErrorSourceDontExists") + sourceFile.getAbsolutePath()); return Status.CANCEL_STATUS; } } Code Sample 2: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); } Code Sample 2: public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; }
11
Code Sample 1: @Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
00
Code Sample 1: private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); } Code Sample 2: 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(); } }
00
Code Sample 1: private BundleURLClassPath createBundleURLClassPath(Bundle bundle, Version version, File bundleFile, File cache, boolean alreadyCached) throws Exception { String bundleClassPath = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClassPath == null) { bundleClassPath = "."; } ManifestEntry[] entries = ManifestEntry.parse(bundleClassPath); String[] classPaths = new String[0]; for (int i = 0; i < entries.length; i++) { String classPath = entries[i].getName(); if (classPath.startsWith("/")) { classPath = classPath.substring(1); } if (classPath.endsWith(".jar")) { try { File file = new File(cache, classPath); if (!alreadyCached) { file.getParentFile().mkdirs(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(classPath).toString(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } else { if (!file.exists()) { throw new IOException(new StringBuilder("classpath ").append(classPath).append(" not found").toString()); } } } catch (IOException e) { FrameworkEvent frameworkEvent = new FrameworkEvent(FrameworkEvent.INFO, bundle, e); framework.postFrameworkEvent(frameworkEvent); continue; } } classPaths = (String[]) ArrayUtil.add(classPaths, classPath); } if (!alreadyCached) { String bundleNativeCode = (String) bundle.getHeaders().get(Constants.BUNDLE_NATIVECODE); if (bundleNativeCode != null) { entries = ManifestEntry.parse(bundleNativeCode); for (int i = 0; i < entries.length; i++) { ManifestEntry entry = entries[i]; String libPath = entry.getName(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(libPath).toString(); File file = new File(cache, libPath); file.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } } } BundleURLClassPath urlClassPath = new BundleURLClassPathImpl(bundle, version, classPaths, cache); return urlClassPath; } Code Sample 2: private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
00
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: public static String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (byte aB : b) { sb.append((Integer.toHexString((aB & 0xFF) | 0x100)).substring(1, 3)); } return sb.toString(); }
00
Code Sample 1: public static void saveFile(final URL url, final File file) throws IOException { final InputStream in = url.openStream(); final FileOutputStream out = new FileOutputStream(file); byte[] data = new byte[8 * 1024]; int length; while ((length = in.read(data)) != -1) { out.write(data, 0, length); } in.close(); out.close(); } Code Sample 2: private boolean loadSymbol(QuoteCache quoteCache, Symbol symbol, TradingDate startDate, TradingDate endDate) { boolean success = true; String URLString = constructURL(symbol, startDate, endDate); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url; url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; while ((line = bufferedInput.readLine()) != null) { Class cl = null; Constructor cnst = null; QuoteFilter filter = null; try { cl = Class.forName("org.mov.quote." + name + "QuoteFilter"); try { cnst = cl.getConstructor(new Class[] { Symbol.class }); } catch (SecurityException e2) { e2.printStackTrace(); } catch (NoSuchMethodException e2) { e2.printStackTrace(); } try { filter = (QuoteFilter) cnst.newInstance(new Object[] { symbol }); } catch (IllegalArgumentException e3) { e3.printStackTrace(); } catch (InstantiationException e3) { e3.printStackTrace(); } catch (IllegalAccessException e3) { e3.printStackTrace(); } catch (InvocationTargetException e3) { e3.printStackTrace(); } } catch (ClassNotFoundException e1) { e1.printStackTrace(); } Quote quote = filter.toQuote(line); if (quote != null) quoteCache.load(quote); } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); success = false; } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); success = false; } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); success = false; } catch (FileNotFoundException e) { } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); success = false; } return success; }
00
Code Sample 1: public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (jmsTemplate == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); if (destinationName != null) jmsTemplate.convertAndSend(destinationName, eventObj); else jmsTemplate.convertAndSend(eventObj); return eventDoc.getEvent().getEventId(); } Code Sample 2: public static String md5(String string) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString((result[i] & 0xFF) | 0x100).toLowerCase().substring(1, 3)); } return hexString.toString(); }
11
Code Sample 1: void copyFile(File inputFile, File outputFile) { try { FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 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) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static byte[] downloadFromUrl(String fileUrl) throws IOException { URL url = new URL(fileUrl); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } return baf.toByteArray(); }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: private void serveCGI(TinyCGI script) throws IOException, TinyWebThreadException { parseHTTPHeaders(); OutputStream cgiOut = null; File tempFile = null; try { if (script == null) sendError(500, "Internal Error", "Couldn't load script."); if (script instanceof TinyCGIHighVolume) { tempFile = File.createTempFile("cgi", null); cgiOut = new FileOutputStream(tempFile); } else { cgiOut = new ByteArrayOutputStream(); } script.service(inputStream, cgiOut, env); } catch (Exception cgie) { this.exceptionEncountered = cgie; if (tempFile != null) tempFile.delete(); if (clientSocket == null) { return; } else if (cgie instanceof TinyCGIException) { TinyCGIException tce = (TinyCGIException) cgie; sendError(tce.getStatus(), tce.getTitle(), tce.getText(), tce.getOtherHeaders()); } else { StringWriter w = new StringWriter(); cgie.printStackTrace(new PrintWriter(w)); sendError(500, "CGI Error", "Error running script: " + "<PRE>" + w.toString() + "</PRE>"); } } finally { if (script != null) doneWithScript(script); } InputStream cgiResults = null; long totalSize = 0; if (tempFile == null) { byte[] results = ((ByteArrayOutputStream) cgiOut).toByteArray(); totalSize = results.length; cgiResults = new ByteArrayInputStream(results); } else { cgiOut.close(); totalSize = tempFile.length(); cgiResults = new FileInputStream(tempFile); } String contentType = null, statusString = "OK", line, header; StringBuffer otherHeaders = new StringBuffer(); StringBuffer text = new StringBuffer(); int status = 200; int headerLength = 0; while (true) { line = readLine(cgiResults, true); headerLength += line.length(); if (line.charAt(0) == '\r' || line.charAt(0) == '\n') break; header = parseHeader(line, text); if (header.toUpperCase().equals("STATUS")) { statusString = text.toString(); status = Integer.parseInt(statusString.substring(0, 3)); statusString = statusString.substring(4); } else if (header.toUpperCase().equals("CONTENT-TYPE")) contentType = text.toString(); else { if (header.toUpperCase().equals("LOCATION")) status = 302; otherHeaders.append(header).append(": ").append(text.toString()).append(CRLF); } } sendHeaders(status, statusString, contentType, totalSize - headerLength, -1, otherHeaders.toString()); byte[] buf = new byte[2048]; int bytesRead; while ((bytesRead = cgiResults.read(buf)) != -1) outputStream.write(buf, 0, bytesRead); outputStream.flush(); try { cgiResults.close(); if (tempFile != null) tempFile.delete(); } catch (IOException ioe) { } }
11
Code Sample 1: private void loadDateFormats() { String fileToLocate = "/" + FILENAME_DATE_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new SimpleDateFormat(parts[1])); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } Code Sample 2: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public static String getTextFromUrl(final String url) { InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(HtmlUtil.quoteHtml(line)).append("\r"); } return result.toString(); } catch (final IOException exception) { return exception.getMessage(); } finally { InputOutputUtil.close(bufferedReader); InputOutputUtil.close(inputStreamReader); } } Code Sample 2: private InputStream openConnection(URL url) throws IOException, DODSException { connection = url.openConnection(); if (acceptDeflate) connection.setRequestProperty("Accept-Encoding", "deflate"); connection.connect(); InputStream is = null; int retry = 1; long backoff = 100L; while (true) { try { is = connection.getInputStream(); break; } catch (NullPointerException e) { System.out.println("DConnect NullPointer; retry open (" + retry + ") " + url); try { Thread.currentThread().sleep(backoff); } catch (InterruptedException ie) { } } catch (FileNotFoundException e) { System.out.println("DConnect FileNotFound; retry open (" + retry + ") " + url); try { Thread.currentThread().sleep(backoff); } catch (InterruptedException ie) { } } if (retry == 3) throw new DODSException("Connection cannot be opened"); retry++; backoff *= 2; } String type = connection.getHeaderField("content-description"); handleContentDesc(is, type); ver = new ServerVersion(connection.getHeaderField("xdods-server")); String encoding = connection.getContentEncoding(); return handleContentEncoding(is, encoding); }
11
Code Sample 1: private void copyFile(File dir, File fileToAdd) { try { byte[] readBuffer = new byte[1024]; File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName()); if (file.createNewFile()) { FileInputStream fis = new FileInputStream(fileToAdd); FileOutputStream fos = new FileOutputStream(file); int bytesRead; do { bytesRead = fis.read(readBuffer); fos.write(readBuffer, 0, bytesRead); } while (bytesRead == 0); fos.flush(); fos.close(); fis.close(); } else { logger.severe("unable to create file:" + file.getAbsolutePath()); } } catch (IOException ioe) { logger.severe("unable to create file:" + ioe); } } Code Sample 2: public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; }
00
Code Sample 1: public void validateClassPath() { try { URL[] urls = ((URLClassLoader) classLoader).getURLs(); for (int i = 0; i < urls.length; i++) { try { urls[i].openStream(); new DebugWriter().writeMessage(urls[i].getFile() + "\n"); } catch (IllegalArgumentException iae) { throw new LinkageError("malformed class path url:\n " + urls[i]); } catch (IOException ioe) { throw new LinkageError("invalid class path url:\n " + urls[i]); } } } catch (ClassCastException e) { throw new IllegalArgumentException("The current VM's System classloader is not a " + "subclass of java.net.URLClassLoader"); } } Code Sample 2: 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); } }
11
Code Sample 1: public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static 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); }
11
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 ResourceMigrator createDefaultResourceMigrator(NotificationReporter reporter, boolean strictMode) throws ResourceMigrationException { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; }
00
Code Sample 1: public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken2", "password")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } Code Sample 2: public String getTemplateString(String templateFilename) { InputStream is = servletContext.getResourceAsStream("/resources/" + templateFilename); StringWriter writer = new StringWriter(); try { IOUtils.copy(is, writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
11
Code Sample 1: protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); } Code Sample 2: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
11
Code Sample 1: private static void copy(File source, File target) throws IOException { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(source)); os = new BufferedOutputStream(new FileOutputStream(target)); int b; while ((b = is.read()) > -1) os.write(b); } finally { try { if (is != null) is.close(); } catch (IOException ignore) { } try { if (os != null) os.close(); } catch (IOException ignore) { } } } Code Sample 2: public void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: @Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: static List<String> listProperties(final MetadataType type) { List<String> props = new ArrayList<String>(); try { File adapter = File.createTempFile("adapter", null); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(type.adapter); if (stream == null) { throw new IllegalStateException("Could not load adapter Jar: " + type.adapter); } FileOutputStream out = new FileOutputStream(adapter); IOUtils.copyLarge(stream, out); out.close(); JarFile jar = new JarFile(adapter); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith("dtd")) { InputStream inputStream = jar.getInputStream(entry); Scanner s = new Scanner(inputStream); while (s.hasNextLine()) { String nextLine = s.nextLine(); if (nextLine.startsWith("<!ELEMENT")) { String prop = nextLine.split(" ")[1]; props.add(prop); } } break; } } } catch (IOException e) { e.printStackTrace(); } return props; }
00
Code Sample 1: public String sendSMS(String host, String port, String username, String password, String from, String to, String text, String uhd, String charset, String coding, String validity, String deferred, String dlrmask, String dlrurl, String pid, String mclass, String mwi) throws SMSPushRequestException, Exception { StringBuffer res = new StringBuffer(); if (!Utils.checkNonEmptyStringAttribute(coding) || coding.equals("0")) text = Utils.convertTextForGSMEncodingURLEncoded(text); else if (coding.equals("1")) text = Utils.convertTextForUTFEncodingURLEncoded(text, "UTF-8"); else text = Utils.convertTextForUTFEncodingURLEncoded(text, "UCS-2"); String directives = "username=" + username; directives += "&password=" + password; directives += "&from=" + URLEncoder.encode(from, "UTF-8"); directives += "&to=" + to; directives += "&text=" + text; if (Utils.checkNonEmptyStringAttribute(uhd)) directives += "&uhd=" + uhd; if (Utils.checkNonEmptyStringAttribute(charset)) directives += "&charset=" + charset; if (Utils.checkNonEmptyStringAttribute(coding)) directives += "&coding=" + coding; if (Utils.checkNonEmptyStringAttribute(validity)) directives += "&validity=" + validity; if (Utils.checkNonEmptyStringAttribute(deferred)) directives += "&deferred=" + deferred; if (Utils.checkNonEmptyStringAttribute(dlrmask)) directives += "&dlrmask=" + dlrmask; if (Utils.checkNonEmptyStringAttribute(dlrurl)) directives += "&dlrurl=" + dlrurl; if (Utils.checkNonEmptyStringAttribute(pid)) directives += "&pid=" + pid; if (Utils.checkNonEmptyStringAttribute(mclass)) directives += "&mclass=" + mclass; if (Utils.checkNonEmptyStringAttribute(mwi)) directives += "&mwi=" + mwi; URL url = new URL("http://" + host + ":" + port + "/cgi-bin/sendsms?" + directives); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response; while ((response = rd.readLine()) != null) res.append(response); rd.close(); String resultCode = res.substring(0, res.indexOf(":")); if (!resultCode.equals(SMS_PUSH_RESPONSE_SUCCESS_CODE)) throw new SMSPushRequestException(resultCode); return res.toString(); } Code Sample 2: private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); }
11
Code Sample 1: private void CopyTo(File dest) throws IOException { FileReader in = null; FileWriter out = null; int c; try { in = new FileReader(image); out = new FileWriter(dest); while ((c = in.read()) != -1) out.write(c); } finally { if (in != null) try { in.close(); } catch (Exception e) { } if (out != null) try { out.close(); } catch (Exception e) { } } } Code Sample 2: public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; }
11
Code Sample 1: public List<String> loadList(String name) { List<String> ret = new ArrayList<String>(); try { URL url = getClass().getClassLoader().getResource("lists/" + name + ".utf-8"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { ret.add(line); } reader.close(); } catch (IOException e) { showError("No se puede cargar la lista de valores: " + name, e); } return ret; } Code Sample 2: public static boolean reportException(Throwable ex, HashMap<String, String> suppl) { if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_CRASH_REPORTING)) { logger.debug("Report exception to devs..."); String data = "reportType=exception&" + "message=" + ex.getMessage(); data += "&build=" + Platform.getBundle("de.uni_mannheim.swt.codeconjurer").getHeaders().get("Bundle-Version"); int ln = 0; for (StackTraceElement el : ex.getStackTrace()) { data += "&st_line_" + ++ln + "=" + el.getClassName() + "#" + el.getMethodName() + "<" + el.getLineNumber() + ">"; } data += "&lines=" + ln; data += "&Suppl-Description=" + ex.toString(); data += "&Suppl-Server=" + Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SERVER); data += "&Suppl-User=" + Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_USERNAME); if (suppl != null) { for (String key : suppl.keySet()) { data += "&Suppl-" + key + "=" + suppl.get(key); } } try { URL url = new URL("http://www.merobase.com:7777/org.code_conjurer.udc/CrashReport"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line + "\r\n"); } writer.close(); reader.close(); logger.debug(answer.toString()); } catch (Exception e) { logger.debug("Could not report exception"); return false; } return true; } else { logger.debug("Reporting not wished!"); return false; } }
11
Code Sample 1: @Override public DownloadingItem download(Playlist playlist, String title, File folder, StopDownloadCondition condition, String uuid) throws IOException, StoreStateException { boolean firstIteration = true; Iterator<PlaylistEntry> entries = playlist.getEntries().iterator(); DownloadingItem prevItem = null; File[] previousDownloadedFiles = new File[0]; while (entries.hasNext()) { PlaylistEntry entry = entries.next(); DownloadingItem item = null; LOGGER.info("Downloading from '" + entry.getTitle() + "'"); InputStream is = RESTHelper.inputStream(entry.getUrl()); boolean stopped = false; File nfile = null; try { nfile = createFileStream(folder, entry); item = new DownloadingItem(nfile, uuid.toString(), title, entry, new Date(), getPID(), condition); if (previousDownloadedFiles.length > 0) { item.setPreviousFiles(previousDownloadedFiles); } addItem(item); if (prevItem != null) deletePrevItem(prevItem); prevItem = item; stopped = IOUtils.copyStreams(is, new FileOutputStream(nfile), condition); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); radioScheduler.fireException(e); if (!condition.isStopped()) { File[] nfiles = new File[previousDownloadedFiles.length + 1]; System.arraycopy(previousDownloadedFiles, 0, nfiles, 0, previousDownloadedFiles.length); nfiles[nfiles.length - 1] = item.getFile(); previousDownloadedFiles = nfiles; if ((!entries.hasNext()) && (firstIteration)) { firstIteration = false; entries = playlist.getEntries().iterator(); } continue; } } if (stopped) { item.setState(ProcessStates.STOPPED); this.radioScheduler.fireStopDownloading(item); return item; } } return null; } Code Sample 2: 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(); }
00
Code Sample 1: public static void copyFolderStucture(String strPath, String dstPath) throws IOException { Constants.iLog.LogInfoLine("copying " + strPath); File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFolderStucture(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } } Code Sample 2: private static String getHash(char[] passwd, String algorithm) throws NoSuchAlgorithmException { MessageDigest alg = MessageDigest.getInstance(algorithm); alg.reset(); alg.update(new String(passwd).getBytes()); byte[] digest = alg.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(0xff & digest[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { Log.debug(fnfe); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public void getZipFiles(String filename) { try { String destinationname = "c:\\mods\\peu\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(filename)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); System.out.println("entryname " + entryName); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: @Override protected Object doInBackground() throws Exception { ArchiveInputStream bufIn = null; FileOutputStream fileOut = null; try { bufIn = DecompressionWorker.guessStream(fileToExtract); ArchiveEntry curZip = null; int progress = 0; while ((curZip = bufIn.getNextEntry()) != null) { if (!curZip.isDirectory()) { byte[] content = new byte[(int) curZip.getSize()]; fileOut = new FileOutputStream(extractionFile.getAbsolutePath() + File.separator + curZip.getName()); for (int i = 0; i < content.length; i++) { fileOut.write(content[i]); } publish(new Integer(progress)); progress++; } } } finally { if (bufIn != null) { bufIn.close(); } } return null; } Code Sample 2: @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnClear) { passwordField.setText(""); } for (int i = 0; i < 10; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; sql = "select password from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } setVisible(false); setTries(0); Error.log(4003, "Senha de uso �nico verificada positivamente."); Error.log(4002, "Autentica��o etapa 3 encerrada."); ManagerWindow mw = new ManagerWindow(login); mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); int tries = getTries(); if (tries == 0) { Error.log(4004, "Primeiro erro da senha de uso �nico contabilizado."); } else if (tries == 1) { Error.log(4005, "Segundo erro da senha de uso �nico contabilizado."); } else if (tries == 2) { Error.log(4006, "Terceiro erro da senha de uso �nico contabilizado."); Error.log(4007, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 3."); Error.log(4002, "Autentica��o etapa 3 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } }
11
Code Sample 1: private static void setEnvEntry(File fromEAR, File toEAR, String ejbJarName, String envEntryName, String envEntryValue) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEAR)); FileOutputStream fos = new FileOutputStream(toEAR); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals(ejbJarName)) { content = editEJBJAR(next, content, envEntryName, envEntryValue); next = new ZipEntry(ejbJarName); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } Code Sample 2: public static void copyFile(File source, File dest) throws Exception { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { throw new Exception("Cannot copy file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(), e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { throw new Exception("Cannot close streams.", e); } } }
00
Code Sample 1: private ArrayList<String> getFiles(String date) { ArrayList<String> files = new ArrayList<String>(); String info = ""; try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS + date + "/"); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf(".bz2"); if (pos != -1) { token = token.substring(1, pos + 4); files.add(token); } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return files; } Code Sample 2: public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; String transferEncoding = null; parts.add(new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) { @Override protected long lengthOfData() throws IOException { return c.getSize(); } @Override protected void sendData(OutputStream out) throws IOException { Reader reader = c.getReader(); try { IOUtils.copy(reader, out); } finally { reader.close(); } } }); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity(new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method.releaseConnection(); method = null; if (is != null) { is.close(); } if ((tries < 1)) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }
11
Code Sample 1: public static String getBiopaxId(Reaction reaction) { String id = null; if (reaction.getId() > Reaction.NO_ID_ASSIGNED) { id = reaction.getId().toString(); } else { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(reaction.getTextualRepresentation().getBytes()); byte[] digestBytes = md.digest(); StringBuilder digesterSb = new StringBuilder(32); for (int i = 0; i < digestBytes.length; i++) { int intValue = digestBytes[i] & 0xFF; if (intValue < 0x10) digesterSb.append('0'); digesterSb.append(Integer.toHexString(intValue)); } id = digesterSb.toString(); } catch (NoSuchAlgorithmException e) { } } return id; } Code Sample 2: public static PipeID getPipeIDForService(ServiceDescriptor descriptor) { PipeID id = null; URI uri = descriptor.getUri(); if (uri != null) { try { id = (PipeID) IDFactory.fromURI(uri); } catch (URISyntaxException e) { throw new RuntimeException("Error creating id for pipe " + uri, e); } } if (id == null) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } String idToHash = descriptor.getName(); if (descriptor.getHost() != null) { idToHash += descriptor.getHost(); } md.update(idToHash.getBytes()); id = IDFactory.newPipeID(InfrastructurePeerGroupID, md.digest()); } return id; }
00
Code Sample 1: @Test(expected = GadgetException.class) public void malformedGadgetSpecThrows() throws Exception { HttpRequest request = createIgnoreCacheRequest(); expect(pipeline.execute(request)).andReturn(new HttpResponse("malformed junk")); replay(pipeline); specFactory.getGadgetSpec(createContext(SPEC_URL, true)); } Code Sample 2: public static String plainToMD(LoggerCollection loggerCol, String input) { byte[] byteHash = null; MessageDigest md = null; StringBuilder md4result = new StringBuilder(); try { md = MessageDigest.getInstance("MD4", new BouncyCastleProvider()); md.reset(); md.update(input.getBytes("UnicodeLittleUnmarked")); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { md4result.append(Integer.toHexString(0xFF & byteHash[i])); } } catch (UnsupportedEncodingException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } catch (NoSuchAlgorithmException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } return (md4result.toString()); }
11
Code Sample 1: public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } } Code Sample 2: public static String cryptSha(String target) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(target.getBytes("UTF-16")); BigInteger res = new BigInteger(1, md.digest(key.getBytes())); return res.toString(16); }
00
Code Sample 1: public static String gerarDigest(String mensagem) { String mensagemCriptografada = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); System.out.println("Mensagem original: " + mensagem); md.update(mensagem.getBytes()); byte[] digest = md.digest(); mensagemCriptografada = converterBytesEmHexa(digest); } catch (Exception e) { e.printStackTrace(); } return mensagemCriptografada; } Code Sample 2: public Resource readResource(URL url, ResourceManager resourceManager) throws NAFException { XMLResource resource = new XMLResource(resourceManager, url); InputStream in = null; try { in = url.openStream(); ArrayList<Transformer> trList = null; Document doc = docbuilder.parse(in); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE && "xml-stylesheet".equals(n.getNodeName())) { ProcessingInstruction pi = (ProcessingInstruction) n; Map<String, String> attrs = DOMUtil.parseProcessingInstructionAttributes(pi); if ("text/xsl".equals(attrs.get("type"))) { String href = attrs.get("href"); if (href == null) throw new NAFException("Style sheet processing instructions must have an \"href\" attribute"); try { Transformer t = styleManager.createTransformer(new URL(url, href)); if (trList == null) trList = new ArrayList<Transformer>(); trList.add(t); } catch (Exception ex) { throw new NAFException("Error reading style sheet resource \"" + href + "\""); } } } } if (trList != null) { for (Transformer t : trList) { doc = (Document) styleManager.transform(t, doc); if (LOGGER_DUMP.isDebugEnabled()) { StringWriter swr = new StringWriter(); DOMUtil.dumpNode(doc, swr); LOGGER_DUMP.debug("Transformed instance:\n" + swr + "\n"); } } } Element rootE = doc.getDocumentElement(); if (!NAF_NAMESPACE_URI.equals(rootE.getNamespaceURI())) throw new NAFException("Root element does not use the NAF namespace"); Object comp = createComponent(rootE, resource, null); resource.setRootObject(comp); return resource; } catch (Exception ex) { throw new NAFException("Error reading NAF resource \"" + url.toExternalForm() + "\"", ex); } finally { if (in != null) try { in.close(); } catch (Exception ignored) { } } }
11
Code Sample 1: public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test1.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.encrypt(reader, writer, key, mode); } Code Sample 2: public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
00
Code Sample 1: public DefaultMainControl(@NotNull final FileFilter scriptFileFilter, @NotNull final String scriptExtension, @NotNull final String scriptName, final int spellType, @Nullable final String spellFile, @NotNull final String scriptsDir, final ErrorView errorView, @NotNull final EditorFactory<G, A, R> editorFactory, final boolean forceReadFromFiles, @NotNull final GlobalSettings globalSettings, @NotNull final ConfigSourceFactory configSourceFactory, @NotNull final PathManager pathManager, @NotNull final GameObjectMatchers gameObjectMatchers, @NotNull final GameObjectFactory<G, A, R> gameObjectFactory, @NotNull final ArchetypeTypeSet archetypeTypeSet, @NotNull final ArchetypeSet<G, A, R> archetypeSet, @NotNull final ArchetypeChooserModel<G, A, R> archetypeChooserModel, @NotNull final AutojoinLists<G, A, R> autojoinLists, @NotNull final AbstractMapManager<G, A, R> mapManager, @NotNull final PluginModel<G, A, R> pluginModel, @NotNull final DelegatingMapValidator<G, A, R> validators, @NotNull final ScriptedEventEditor<G, A, R> scriptedEventEditor, @NotNull final AbstractResources<G, A, R> resources, @NotNull final Spells<NumberSpell> numberSpells, @NotNull final Spells<GameObjectSpell<G, A, R>> gameObjectSpells, @NotNull final PluginParameterFactory<G, A, R> pluginParameterFactory, @NotNull final ValidatorPreferences validatorPreferences, @NotNull final MapWriter<G, A, R> mapWriter) { final XmlHelper xmlHelper; try { xmlHelper = new XmlHelper(); } catch (final ParserConfigurationException ex) { log.fatal("Cannot create XML parser: " + ex.getMessage()); throw new MissingResourceException("Cannot create XML parser: " + ex.getMessage(), null, null); } final AttributeRangeChecker<G, A, R> attributeRangeChecker = new AttributeRangeChecker<G, A, R>(validatorPreferences); final EnvironmentChecker<G, A, R> environmentChecker = new EnvironmentChecker<G, A, R>(validatorPreferences); final DocumentBuilder documentBuilder = xmlHelper.getDocumentBuilder(); try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), "GameObjectMatchers.xml"); final ErrorViewCollector gameObjectMatchersErrorViewCollector = new ErrorViewCollector(errorView, url); try { documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(gameObjectMatchersErrorViewCollector, ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID)); try { final GameObjectMatchersParser gameObjectMatchersParser = new GameObjectMatchersParser(documentBuilder, xmlHelper.getXPath()); gameObjectMatchersParser.readGameObjectMatchers(url, gameObjectMatchers, gameObjectMatchersErrorViewCollector); } finally { documentBuilder.setErrorHandler(null); } } catch (final IOException ex) { gameObjectMatchersErrorViewCollector.addWarning(ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID, ex.getMessage()); } final ValidatorFactory<G, A, R> validatorFactory = new ValidatorFactory<G, A, R>(validatorPreferences, gameObjectMatchers, globalSettings, mapWriter); loadValidators(validators, validatorFactory, errorView); editorFactory.initMapValidators(validators, gameObjectMatchersErrorViewCollector, globalSettings, gameObjectMatchers, attributeRangeChecker, validatorPreferences); validators.addValidator(attributeRangeChecker); validators.addValidator(environmentChecker); } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID, "GameObjectMatchers.xml: " + ex.getMessage()); } final GameObjectMatcher shopSquareMatcher = gameObjectMatchers.getMatcher("system_shop_square", "shop_square"); if (shopSquareMatcher != null) { final GameObjectMatcher noSpellsMatcher = gameObjectMatchers.getMatcher("system_no_spells", "no_spells"); if (noSpellsMatcher != null) { final GameObjectMatcher blockedMatcher = gameObjectMatchers.getMatcher("system_blocked", "blocked"); validators.addValidator(new ShopSquareChecker<G, A, R>(validatorPreferences, shopSquareMatcher, noSpellsMatcher, blockedMatcher)); } final GameObjectMatcher paidItemMatcher = gameObjectMatchers.getMatcher("system_paid_item"); if (paidItemMatcher != null) { validators.addValidator(new PaidItemShopSquareChecker<G, A, R>(validatorPreferences, shopSquareMatcher, paidItemMatcher)); } } Map<String, TreasureTreeNode> specialTreasureLists; try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), "TreasureLists.xml"); final ErrorViewCollector treasureListsErrorViewCollector = new ErrorViewCollector(errorView, url); try { final InputStream inputStream = url.openStream(); try { documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(treasureListsErrorViewCollector, ErrorViewCategory.TREASURES_FILE_INVALID)); try { final Document specialTreasureListsDocument = documentBuilder.parse(new InputSource(inputStream)); specialTreasureLists = TreasureListsParser.parseTreasureLists(specialTreasureListsDocument); } finally { documentBuilder.setErrorHandler(null); } } finally { inputStream.close(); } } catch (final IOException ex) { treasureListsErrorViewCollector.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } catch (final SAXException ex) { treasureListsErrorViewCollector.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, "TreasureLists.xml: " + ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } final ConfigSource configSource = forceReadFromFiles ? configSourceFactory.getFilesConfigSource() : configSourceFactory.getConfigSource(globalSettings.getConfigSourceName()); treasureTree = TreasureLoader.parseTreasures(errorView, specialTreasureLists, configSource, globalSettings); final ArchetypeAttributeFactory archetypeAttributeFactory = new DefaultArchetypeAttributeFactory(); final ArchetypeAttributeParser archetypeAttributeParser = new ArchetypeAttributeParser(archetypeAttributeFactory); final ArchetypeTypeParser archetypeTypeParser = new ArchetypeTypeParser(archetypeAttributeParser); ArchetypeTypeList eventTypeSet = null; try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), CommonConstants.TYPEDEF_FILE); final ErrorViewCollector typesErrorViewCollector = new ErrorViewCollector(errorView, url); documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(typesErrorViewCollector, ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID)); try { final ArchetypeTypeSetParser archetypeTypeSetParser = new ArchetypeTypeSetParser(documentBuilder, archetypeTypeSet, archetypeTypeParser); archetypeTypeSetParser.loadTypesFromXML(typesErrorViewCollector, new InputSource(url.toString())); } finally { documentBuilder.setErrorHandler(null); } final ArchetypeTypeList eventTypeSetTmp = archetypeTypeSet.getList("event"); if (eventTypeSetTmp == null) { typesErrorViewCollector.addWarning(ErrorViewCategory.TYPES_ENTRY_INVALID, "list 'list_event' does not exist"); } else { eventTypeSet = eventTypeSetTmp; } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.TYPES_FILE_INVALID, CommonConstants.TYPEDEF_FILE + ": " + ex.getMessage()); } if (eventTypeSet == null) { eventTypeSet = new ArchetypeTypeList(); } scriptArchUtils = editorFactory.newScriptArchUtils(eventTypeSet); final ScriptedEventFactory<G, A, R> scriptedEventFactory = editorFactory.newScriptedEventFactory(scriptArchUtils, gameObjectFactory, scriptedEventEditor, archetypeSet); scriptArchEditor = new DefaultScriptArchEditor<G, A, R>(scriptedEventFactory, scriptExtension, scriptName, scriptArchUtils, scriptFileFilter, globalSettings, mapManager, pathManager); scriptedEventEditor.setScriptArchEditor(scriptArchEditor); scriptArchData = editorFactory.newScriptArchData(); scriptArchDataUtils = editorFactory.newScriptArchDataUtils(scriptArchUtils, scriptedEventFactory, scriptedEventEditor); final long timeStart = System.currentTimeMillis(); if (log.isInfoEnabled()) { log.info("Start to load archetypes..."); } configSource.read(globalSettings, resources, errorView); for (final R archetype : archetypeSet.getArchetypes()) { final CharSequence editorFolder = archetype.getEditorFolder(); if (editorFolder != null && !editorFolder.equals(GameObject.EDITOR_FOLDER_INTERN)) { final String[] tmp = StringUtils.PATTERN_SLASH.split(editorFolder, 2); if (tmp.length == 2) { final String panelName = tmp[0]; final String folderName = tmp[1]; archetypeChooserModel.addArchetype(panelName, folderName, archetype); } } } if (log.isInfoEnabled()) { log.info("Archetype loading took " + (double) (System.currentTimeMillis() - timeStart) / 1000.0 + " seconds."); } if (spellType != 0) { new ArchetypeSetSpellLoader<G, A, R>(gameObjectFactory).load(archetypeSet, spellType, gameObjectSpells); gameObjectSpells.sort(); } if (spellFile != null) { try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), spellFile); final ErrorViewCollector errorViewCollector = new ErrorViewCollector(errorView, url); documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(errorViewCollector, ErrorViewCategory.SPELLS_FILE_INVALID)); try { XMLSpellLoader.load(errorViewCollector, url, xmlHelper.getDocumentBuilder(), numberSpells); } finally { documentBuilder.setErrorHandler(null); } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.SPELLS_FILE_INVALID, spellFile + ": " + ex.getMessage()); } numberSpells.sort(); } final File scriptsFile = new File(globalSettings.getMapsDirectory(), scriptsDir); final PluginModelParser<G, A, R> pluginModelParser = new PluginModelParser<G, A, R>(pluginParameterFactory); new PluginModelLoader<G, A, R>(pluginModelParser).loadPlugins(errorView, scriptsFile, pluginModel); new AutojoinListsParser<G, A, R>(errorView, archetypeSet, autojoinLists).loadList(globalSettings.getConfigurationDirectory()); ArchetypeTypeChecks.addChecks(archetypeTypeSet, attributeRangeChecker, environmentChecker); } Code Sample 2: private boolean canReadSource(String fileURL) { URL url; try { url = new URL(fileURL); } catch (MalformedURLException e) { log.error("Error accessing URL " + fileURL + "."); return false; } InputStream is; try { is = url.openStream(); } catch (IOException e) { log.error("Error creating Input Stream from URL '" + fileURL + "'."); return false; } return true; }
11
Code Sample 1: public String hash(String plainTextPassword) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(plainTextPassword.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(org.jboss.seam.util.Hex.encodeHex(rawHash)); } catch (NoSuchAlgorithmException e) { log.error("Digest algorithm #0 to calculate the password hash will not be supported.", digestAlgorithm); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { log.error("The Character Encoding #0 is not supported", charset); throw new RuntimeException(e); } } Code Sample 2: protected String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception ex) { throw new TiiraException(ex); } }
11
Code Sample 1: public void readData(RowSetInternal caller) throws SQLException { Connection con = null; try { CachedRowSet crs = (CachedRowSet) caller; if (crs.getPageSize() == 0 && crs.size() > 0) { crs.close(); } writerCalls = 0; userCon = false; con = this.connect(caller); if (con == null || crs.getCommand() == null) throw new SQLException(resBundle.handleGetObject("crsreader.connecterr").toString()); try { con.setTransactionIsolation(crs.getTransactionIsolation()); } catch (Exception ex) { ; } PreparedStatement pstmt = con.prepareStatement(crs.getCommand()); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } if (crs.getCommand().toLowerCase().indexOf("select") != -1) { ResultSet rs = pstmt.executeQuery(); if (crs.getPageSize() == 0) { crs.populate(rs); } else { pstmt = con.prepareStatement(crs.getCommand(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } rs = pstmt.executeQuery(); crs.populate(rs, startPosition); } rs.close(); } else { pstmt.executeUpdate(); } pstmt.close(); try { con.commit(); } catch (SQLException ex) { ; } if (getCloseConnection() == true) con.close(); } catch (SQLException ex) { throw ex; } finally { try { if (con != null && getCloseConnection() == true) { try { if (!con.getAutoCommit()) { con.rollback(); } } catch (Exception dummy) { } con.close(); con = null; } } catch (SQLException e) { } } } Code Sample 2: public boolean save(Object obj) { boolean bool = false; this.result = null; if (obj == null) return bool; Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, obj); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; }
11
Code Sample 1: private void extractSourceFiles(String jar) { JarInputStream in = null; BufferedOutputStream out = null; try { in = new JarInputStream(new FileInputStream(getProjectFile(jar))); JarEntry item; byte buffer[] = new byte[4096]; int buflength; while ((item = in.getNextJarEntry()) != null) if (item.getName().startsWith(PREFIX) && (!item.getName().endsWith("/"))) { out = new BufferedOutputStream(new FileOutputStream(new File(dest, getFileName(item)))); while ((buflength = in.read(buffer)) != -1) out.write(buffer, 0, buflength); howmany++; out.flush(); out.close(); out = null; } } catch (IOException ex) { System.out.println("Unable to parse file " + jar + ", reason: " + ex.getMessage()); } finally { try { if (in != null) in.close(); } catch (IOException ex) { } try { if (out != null) out.close(); } catch (IOException ex) { } } } Code Sample 2: public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
11
Code Sample 1: public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } Code Sample 2: public void zipDocsetFiles(SaxHandler theXmlHandler, int theEventId, Attributes theAtts) throws BpsProcessException { ZipOutputStream myZipOut = null; BufferedInputStream myDocumentInputStream = null; String myFinalFile = null; String myTargetPath = null; String myTargetFileName = null; String myInputFileName = null; byte[] myBytesBuffer = null; int myLength = 0; try { myZipOut = new ZipOutputStream(new FileOutputStream(myFinalFile)); myZipOut.putNextEntry(new ZipEntry(myTargetPath + myTargetFileName)); myDocumentInputStream = new BufferedInputStream(new FileInputStream(myInputFileName)); while ((myLength = myDocumentInputStream.read(myBytesBuffer, 0, 4096)) != -1) myZipOut.write(myBytesBuffer, 0, myLength); myZipOut.closeEntry(); myZipOut.close(); } catch (FileNotFoundException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "FileNotFoundException while building zip dest file")); } catch (IOException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "IOException while building zip dest file")); } }
11
Code Sample 1: public TVRageShowInfo(String xmlShowName, String xmlSearchBy) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime") && tmp.length > 1) { airTime = tmp[1]; } } if (airTime.length() > 10) { tmp = airTime.split("at"); airTimeHour = tmp[1]; } in.close(); if (xmlSearchBy.equals("Showname SeriesNum")) { url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[5].indexOf(':') > -1) { tmp = tmp[5].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[3].indexOf(':') > -1) { tmp = tmp[3].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); }
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 salva(UploadedFile imagem, Usuario usuario) { File destino; if (usuario.getId() == null) { destino = new File(pastaImagens, usuario.hashCode() + ".jpg"); } else { destino = new File(pastaImagens, usuario.getId() + ".jpg"); } try { IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino)); } catch (Exception e) { throw new RuntimeException("Erro ao copiar imagem", e); } redimensionar(destino.getPath(), destino.getPath(), "jpg", 110, 110); }
11
Code Sample 1: public void copyToCurrentDir(File _copyFile, String _fileName) throws IOException { File outputFile = new File(getCurrentPath() + File.separator + _fileName); FileReader in; FileWriter out; if (!outputFile.exists()) { outputFile.createNewFile(); } in = new FileReader(_copyFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); reList(); } Code Sample 2: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; }
00
Code Sample 1: public static String encrypt(String plainText) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: private Tuple execute(final HttpMethodBase method, int numTries) throws IOException { final Timer timer = Metric.newTimer("RestClientImpl.execute"); try { final int sc = httpClient.executeMethod(method); if (sc < OK_MIN || sc > OK_MAX) { throw new RestException("Unexpected status code: " + sc + ": " + method.getStatusText() + " -- " + method, sc); } final InputStream in = method.getResponseBodyAsStream(); try { final StringWriter writer = new StringWriter(2048); IOUtils.copy(in, writer, method.getResponseCharSet()); return new Tuple(sc, writer.toString()); } finally { in.close(); } } catch (NullPointerException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (SocketException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (IOException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw e; } finally { method.releaseConnection(); timer.stop(); } }
11
Code Sample 1: public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(destination).getChannel(); long size = in.size(); MappedByteBuffer buffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buffer); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
00
Code Sample 1: public void mousePressed(MouseEvent e) { bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(bannerURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); HttpHost host = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); String targetURL = host.toURI() + request.getURI(); DesktopUtil.browseAndWarn(targetURL, bannerLbl); EntityUtils.consume(entity); } catch (Exception ex) { NotifyUtil.error("Banner Error", "Could not open the default web browser.", ex, false); } finally { method.abort(); } bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } Code Sample 2: public static void main(String[] args) { JFileChooser askDir = new JFileChooser(); askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); askDir.setMultiSelectionEnabled(false); int returnVal = askDir.showOpenDialog(null); if (returnVal == JFileChooser.CANCEL_OPTION) { System.exit(returnVal); } File startDir = askDir.getSelectedFile(); ArrayList<File> files = new ArrayList<File>(); goThrough(startDir, files); SearchClient client = new SearchClient("VZFo5W5i"); MyID3 singleton = new MyID3(); for (File song : files) { try { MusicMetadataSet set = singleton.read(song); IMusicMetadata meta = set.getSimplified(); String qu = song.getName(); if (meta.getAlbum() != null) { qu = meta.getAlbum(); } else if (meta.getArtist() != null) { qu = meta.getArtist(); } if (qu.length() > 2) { ImageSearchRequest req = new ImageSearchRequest(qu); ImageSearchResults res = client.imageSearch(req); if (res.getTotalResultsAvailable().doubleValue() > 1) { System.out.println("Downloading " + res.listResults()[0].getUrl()); URL url = new URL(res.listResults()[0].getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); int realSize = con.getContentLength(); if (realSize > 0) { String mime = con.getContentType(); InputStream stream = con.getInputStream(); byte[] realData = new byte[realSize]; for (int i = 0; i < realSize; i++) { stream.read(realData, i, 1); } stream.close(); ImageData imgData = new ImageData(realData, mime, qu, 0); meta.addPicture(imgData); File temp = File.createTempFile("tempsong", "mp3"); singleton.write(song, temp, set, meta); FileChannel inChannel = new FileInputStream(temp).getChannel(); FileChannel outChannel = new FileOutputStream(song).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } temp.delete(); } } } } catch (ID3ReadException e) { } catch (MalformedURLException e) { } catch (UnsupportedEncodingException e) { } catch (ID3WriteException e) { } catch (IOException e) { } catch (SearchException e) { } } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2008Apr cb = new AcmSearchresultPageParser_2008Apr(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartposisions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartposisions().get(i); System.out.println(i + "pos= " + m); } }
11
Code Sample 1: public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
00
Code Sample 1: public static int executeUpdate(EOAdaptorChannel channel, String sql, boolean autoCommit) throws SQLException { int rowsUpdated; boolean wasOpen = channel.isOpen(); if (!wasOpen) { channel.openChannel(); } Connection conn = ((JDBCContext) channel.adaptorContext()).connection(); try { Statement stmt = conn.createStatement(); try { rowsUpdated = stmt.executeUpdate(sql); if (autoCommit) { conn.commit(); } } catch (SQLException ex) { if (autoCommit) { conn.rollback(); } throw new RuntimeException("Failed to execute the statement '" + sql + "'.", ex); } finally { stmt.close(); } } finally { if (!wasOpen) { channel.closeChannel(); } } return rowsUpdated; } Code Sample 2: @Override protected void doPost(final String url, final InputStream data) throws WebServiceException { final HttpPost method = new HttpPost(url); method.setEntity(new InputStreamEntity(data, -1)); try { final HttpResponse response = this.httpClient.execute(method); final String responseString = response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : ""; final int statusCode = response.getStatusLine().getStatusCode(); switch(statusCode) { case HttpStatus.SC_OK: return; case HttpStatus.SC_NOT_FOUND: throw new ResourceNotFoundException(responseString); case HttpStatus.SC_BAD_REQUEST: throw new RequestException(responseString); case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException(responseString); case HttpStatus.SC_UNAUTHORIZED: throw new AuthorizationException(responseString); default: String em = "web service returned unknown status '" + statusCode + "', response was: " + responseString; this.log.error(em); throw new WebServiceException(em); } } catch (IOException e) { this.log.error("Fatal transport error: " + e.getMessage()); throw new WebServiceException(e.getMessage(), e); } }
00
Code Sample 1: public void actionPerformed(ActionEvent evt) { try { File tempFile = new File("/tmp/controler.xml"); File f = new File("/tmp/controler-temp.xml"); BufferedInputStream copySource = new BufferedInputStream(new FileInputStream(tempFile)); BufferedOutputStream copyDestination = new BufferedOutputStream(new FileOutputStream(f)); int read = 0; while (read != -1) { read = copySource.read(buffer, 0, BUFFER_SIZE); if (read != -1) { copyDestination.write(buffer, 0, read); } } copyDestination.write(new String("</log>\n").getBytes()); copySource.close(); copyDestination.close(); XMLParser parser = new XMLParser("Controler"); parser.parse(f); f.delete(); } catch (IOException ex) { System.out.println("An error occured during the file copy!"); } } Code Sample 2: public static String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
11
Code Sample 1: private static long copy(InputStream source, OutputStream sink) { try { return IOUtils.copyLarge(source, sink); } catch (IOException e) { throw new FaultException("System error copying stream", e); } finally { IOUtils.closeQuietly(source); IOUtils.closeQuietly(sink); } } Code Sample 2: private void addAllSpecialPages(Environment env, ZipOutputStream zipout, int progressStart, int progressLength) throws Exception, IOException { ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale); String tpl; int count = 0; int numberOfSpecialPages = 7; progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; String cssContent = wb.readRaw(virtualWiki, "StyleSheet"); addZipEntry(zipout, "css/vqwiki.css", cssContent); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; tpl = getTemplateFilledWithContent("search"); addTopicEntry(zipout, tpl, "WikiSearch", "WikiSearch.html"); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; zipout.putNextEntry(new ZipEntry("applets/export2html-applet.jar")); IOUtils.copy(new FileInputStream(ctx.getRealPath("/WEB-INF/classes/export2html/export2html-applet.jar")), zipout); zipout.closeEntry(); zipout.flush(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JarOutputStream indexjar = new JarOutputStream(bos); JarEntry jarEntry; File searchDir = new File(wb.getSearchEngine().getSearchIndexPath(virtualWiki)); String files[] = searchDir.list(); StringBuffer listOfAllFiles = new StringBuffer(); for (int i = 0; i < files.length; i++) { if (listOfAllFiles.length() > 0) { listOfAllFiles.append(","); } listOfAllFiles.append(files[i]); jarEntry = new JarEntry("lucene/index/" + files[i]); indexjar.putNextEntry(jarEntry); IOUtils.copy(new FileInputStream(new File(searchDir, files[i])), indexjar); indexjar.closeEntry(); } indexjar.flush(); indexjar.putNextEntry(new JarEntry("lucene/index.dir")); IOUtils.copy(new StringReader(listOfAllFiles.toString()), indexjar); indexjar.closeEntry(); indexjar.flush(); indexjar.close(); zipout.putNextEntry(new ZipEntry("applets/index.jar")); zipout.write(bos.toByteArray()); zipout.closeEntry(); zipout.flush(); bos.reset(); } catch (Exception e) { logger.log(Level.FINE, "Exception while adding lucene index: ", e); } progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; StringBuffer content = new StringBuffer(); content.append("<table><tr><th>" + messages.getString("common.date") + "</th><th>" + messages.getString("common.topic") + "</th><th>" + messages.getString("common.user") + "</th></tr>" + IOUtils.LINE_SEPARATOR); Collection all = null; try { Calendar cal = Calendar.getInstance(); ChangeLog cl = wb.getChangeLog(); int n = env.getIntSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS); if (n == 0) { n = 5; } all = new ArrayList(); for (int i = 0; i < n; i++) { Collection col = cl.getChanges(virtualWiki, cal.getTime()); if (col != null) { all.addAll(col); } cal.add(Calendar.DATE, -1); } } catch (Exception e) { } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); for (Iterator iter = all.iterator(); iter.hasNext(); ) { Change change = (Change) iter.next(); content.append("<tr><td class=\"recent\">" + df.format(change.getTime()) + "</td><td class=\"recent\"><a href=\"" + safename(change.getTopic()) + ".html\">" + change.getTopic() + "</a></td><td class=\"recent\">" + change.getUser() + "</td></tr>"); } content.append("</table>" + IOUtils.LINE_SEPARATOR); tpl = getTemplateFilledWithContent(null); tpl = tpl.replaceAll("@@CONTENTS@@", content.toString()); addTopicEntry(zipout, tpl, "RecentChanges", "RecentChanges.html"); logger.fine("Done adding all special topics."); }
00
Code Sample 1: public static boolean isUrlAvailable(String url) { boolean flag = true; try { URLConnection conn = (new URL(url)).openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.connect(); if (conn.getDate() == 0) { flag = false; } } catch (IOException e) { log.error(e); flag = false; } return flag; } Code Sample 2: private boolean loadNodeData(NodeInfo info) { String query = mServer + "load.php" + ("?id=" + info.getId()) + ("&mask=" + NodePropertyFlag.Data); boolean rCode = false; try { URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); conn.setRequestMethod("GET"); setCredentials(conn); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = conn.getInputStream(); byte[] data = new byte[0], temp = new byte[1024]; boolean eof = false; while (!eof) { int read = stream.read(temp); if (read > 0) { byte[] buf = new byte[data.length + read]; System.arraycopy(data, 0, buf, 0, data.length); System.arraycopy(temp, 0, buf, data.length, read); data = buf; } else if (read < 0) { eof = true; } } info.setData(data); info.setMIMEType(new MimeType(conn.getContentType())); rCode = true; stream.close(); } } catch (Exception ex) { } return rCode; }
00
Code Sample 1: private BufferedReader getReader(final String fileUrl) throws IOException { InputStreamReader reader; try { reader = new FileReader(fileUrl); } catch (FileNotFoundException e) { URL url = new URL(fileUrl); reader = new InputStreamReader(url.openStream()); } return new BufferedReader(reader); } Code Sample 2: public void initialize(IProgressMonitor monitor) throws JETException { IProgressMonitor progressMonitor = monitor; progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_GeneratingJETEmitterFor_message", new Object[] { getTemplateURI() })); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { final JETCompiler jetCompiler = getTemplateURIPath() == null ? new MyBaseJETCompiler(getTemplateURI(), getEncoding(), getClassLoader()) : new MyBaseJETCompiler(getTemplateURIPath(), getTemplateURI(), getEncoding(), getClassLoader()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETParsing_message", new Object[] { jetCompiler.getResolvedTemplateURI() })); jetCompiler.parse(); progressMonitor.worked(1); String packageName = jetCompiler.getSkeleton().getPackageName(); if (getTemplateURIPath() != null) { URI templateURI = URI.createURI(getTemplateURIPath()[0]); URLClassLoader theClassLoader = null; if (templateURI.isPlatformResource()) { IProject project = workspace.getRoot().getProject(templateURI.segment(1)); if (JETNature.getRuntime(project) != null) { List<URL> urls = new ArrayList<URL>(); IJavaProject javaProject = JavaCore.create(project); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = classpathEntry.getPath(); IProject otherProject = workspace.getRoot().getProject(projectPath.segment(0)); IJavaProject otherJavaProject = JavaCore.create(otherProject); urls.add(new File(otherProject.getLocation() + "/" + otherJavaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); } } theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperAction(urls)); } } else if (templateURI.isPlatformPlugin()) { final Bundle bundle = Platform.getBundle(templateURI.segment(1)); if (bundle != null) { theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderBundleAction(bundle)); } } if (theClassLoader != null) { String className = (packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName(); if (className.endsWith("_")) { className = className.substring(0, className.length() - 1); } try { Class<?> theClass = theClassLoader.loadClass(className); Class<?> theOtherClass = null; try { theOtherClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException exception) { } if (theClass != theOtherClass) { String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } return; } } catch (ClassNotFoundException exception) { } } } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jetCompiler.generate(outputStream); final InputStream contents = new ByteArrayInputStream(outputStream.toByteArray()); if (!javaModel.isOpen()) { javaModel.open(new SubProgressMonitor(progressMonitor, 1)); } else { progressMonitor.worked(1); } final IProject project = workspace.getRoot().getProject(jetEmitter.getProjectName()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETPreparingProject_message", new Object[] { project.getName() })); IJavaProject javaProject; if (!project.exists()) { progressMonitor.subTask("JET creating project " + project.getName()); project.create(new SubProgressMonitor(progressMonitor, 1)); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreatingProject_message", new Object[] { project.getName() })); IProjectDescription description = workspace.newProjectDescription(project.getName()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); description.setLocation(null); project.open(new SubProgressMonitor(progressMonitor, 1)); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } else { project.open(new SubProgressMonitor(progressMonitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } javaProject = JavaCore.create(project); List<IClasspathEntry> classpath = new UniqueEList<IClasspathEntry>(Arrays.asList(javaProject.getRawClasspath())); for (int i = 0, len = classpath.size(); i < len; i++) { IClasspathEntry entry = classpath.get(i); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && ("/" + project.getName()).equals(entry.getPath().toString())) { classpath.remove(i); } } progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETInitializingProject_message", new Object[] { project.getName() })); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(new Path("/" + project.getName() + "/src")); IClasspathEntry jreClasspathEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); classpath.add(classpathEntry); classpath.add(jreClasspathEntry); classpath.addAll(getClassPathEntries()); IFolder sourceFolder = project.getFolder(new Path("src")); if (!sourceFolder.exists()) { sourceFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } IFolder runtimeFolder = project.getFolder(new Path("bin")); if (!runtimeFolder.exists()) { runtimeFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), new SubProgressMonitor(progressMonitor, 1)); javaProject.setOutputLocation(new Path("/" + project.getName() + "/bin"), new SubProgressMonitor(progressMonitor, 1)); javaProject.close(); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETOpeningJavaProject_message", new Object[] { project.getName() })); javaProject.open(new SubProgressMonitor(progressMonitor, 1)); IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); IPackageFragmentRoot sourcePackageFragmentRoot = null; for (int j = 0; j < packageFragmentRoots.length; ++j) { IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[j]; if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { sourcePackageFragmentRoot = packageFragmentRoot; break; } } StringTokenizer stringTokenizer = new StringTokenizer(packageName, "."); IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1); subProgressMonitor.beginTask("", stringTokenizer.countTokens() + 4); subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_CreateTargetFile_message")); IContainer sourceContainer = sourcePackageFragmentRoot == null ? project : (IContainer) sourcePackageFragmentRoot.getCorrespondingResource(); while (stringTokenizer.hasMoreElements()) { String folderName = stringTokenizer.nextToken(); sourceContainer = sourceContainer.getFolder(new Path(folderName)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(subProgressMonitor, 1)); } } IFile targetFile = sourceContainer.getFile(new Path(jetCompiler.getSkeleton().getClassName() + ".java")); if (!targetFile.exists()) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreating_message", new Object[] { targetFile.getFullPath() })); targetFile.create(contents, true, new SubProgressMonitor(subProgressMonitor, 1)); } else { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdating_message", new Object[] { targetFile.getFullPath() })); targetFile.setContents(contents, true, true, new SubProgressMonitor(subProgressMonitor, 1)); } subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETBuilding_message", new Object[] { project.getName() })); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(subProgressMonitor, 1)); boolean errors = hasErrors(subProgressMonitor, targetFile); if (!errors) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETLoadingClass_message", new Object[] { jetCompiler.getSkeleton().getClassName() + ".class" })); List<URL> urls = new ArrayList<URL>(); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); final Set<Bundle> bundles = new HashSet<Bundle>(); LOOP: for (IClasspathEntry jetEmitterClasspathEntry : jetEmitter.getClasspathEntries()) { IClasspathAttribute[] classpathAttributes = jetEmitterClasspathEntry.getExtraAttributes(); if (classpathAttributes != null) { for (IClasspathAttribute classpathAttribute : classpathAttributes) { if (classpathAttribute.getName().equals(CodeGenUtil.EclipseUtil.PLUGIN_ID_CLASSPATH_ATTRIBUTE_NAME)) { Bundle bundle = Platform.getBundle(classpathAttribute.getValue()); if (bundle != null) { bundles.add(bundle); continue LOOP; } } } } urls.add(new URL("platform:/resource" + jetEmitterClasspathEntry.getPath() + "/")); } URLClassLoader theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperBundlesAction(bundles, urls)); Class<?> theClass = theClassLoader.loadClass((packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName()); String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } } subProgressMonitor.done(); } catch (CoreException exception) { throw new JETException(exception); } catch (Exception exception) { throw new JETException(exception); } finally { progressMonitor.done(); } }
11
Code Sample 1: public void processDeleteCompany(Company companyBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (companyBean.getId() == null) throw new IllegalArgumentException("companyId is null"); String sql = "update WM_LIST_COMPANY set is_deleted = 1 " + "where ID_FIRM = ? and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, companyBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(2, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public void removerTopicos(Topicos topicos) throws ClassNotFoundException, SQLException { this.criaConexao(false); String sql = "DELETE FROM \"Topicos\" " + " WHERE \"id_Topicos\" = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, topicos.getIdTopicos()); stmt.executeUpdate(); connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
00
Code Sample 1: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } } Code Sample 2: public void testDecodeJTLM_publish100() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.DEFAULT_OPTIONS); String[] exiFiles = { "/JTLM/publish100/publish100.bitPacked", "/JTLM/publish100/publish100.byteAligned", "/JTLM/publish100/publish100.preCompress", "/JTLM/publish100/publish100.compress" }; for (int i = 0; i < Alignments.length; i++) { AlignmentType alignment = Alignments[i]; EXIDecoder decoder = new EXIDecoder(); Scanner scanner; decoder.setAlignmentType(alignment); URL url = resolveSystemIdAsURL(exiFiles[i]); int n_events, n_texts; decoder.setEXISchema(grammarCache); decoder.setInputStream(url.openStream()); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { String stringValue = exiEvent.getCharacters().makeString(); if (stringValue.length() == 0 && exiEvent.getEventType().itemType == EventCode.ITEM_SCHEMA_CH) { --n_events; continue; } if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(publish100_centennials[n], stringValue); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(10610, n_events); } }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public 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(); } }
00
Code Sample 1: public String getScenarioData(String urlForSalesData) throws IOException, Exception { InputStream inputStream = null; BufferedReader bufferedReader = null; DataInputStream input = null; StringBuffer sBuf = new StringBuffer(); Proxy proxy; if (httpWebProxyServer != null && Integer.toString(httpWebProxyPort) != null) { SocketAddress address = new InetSocketAddress(httpWebProxyServer, httpWebProxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); } else { proxy = null; } proxy = null; URL url; try { url = new URL(urlForSalesData); HttpURLConnection httpUrlConnection; if (proxy != null) httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); else httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setDoInput(true); httpUrlConnection.setRequestMethod("GET"); String name = rb.getString("WRAP_NAME"); String password = rb.getString("WRAP_PASSWORD"); Credentials simpleAuthCrentials = new Credentials(TOKEN_TYPE.SimpleApiAuthToken, name, password); ACSTokenProvider tokenProvider = new ACSTokenProvider(httpWebProxyServer, httpWebProxyPort, simpleAuthCrentials); String requestUriStr1 = "https://" + solutionName + "." + acmHostName + "/" + serviceName; String appliesTo1 = rb.getString("SIMPLEAPI_APPLIES_TO"); String token = tokenProvider.getACSToken(requestUriStr1, appliesTo1); httpUrlConnection.addRequestProperty("token", "WRAPv0.9 " + token); httpUrlConnection.addRequestProperty("solutionName", solutionName); httpUrlConnection.connect(); if (httpUrlConnection.getResponseCode() == HttpServletResponse.SC_UNAUTHORIZED) { List<TestSalesOrderService> salesOrderServiceBean = new ArrayList<TestSalesOrderService>(); TestSalesOrderService response = new TestSalesOrderService(); response.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); response.setResponseMessage(httpUrlConnection.getResponseMessage()); salesOrderServiceBean.add(response); } inputStream = httpUrlConnection.getInputStream(); input = new DataInputStream(inputStream); bufferedReader = new BufferedReader(new InputStreamReader(input)); String str; while (null != ((str = bufferedReader.readLine()))) { sBuf.append(str); } String responseString = sBuf.toString(); return responseString; } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } } Code Sample 2: private void downloadDirectory() throws SocketException, IOException { FTPClient client = new FTPClient(); client.connect(source.getHost()); client.login(username, password); FTPFile[] files = client.listFiles(source.getPath()); for (FTPFile file : files) { if (!file.isDirectory()) { long file_size = file.getSize() / 1024; Calendar cal = file.getTimestamp(); URL source_file = new File(source + file.getName()).toURI().toURL(); DownloadQueue.add(new Download(projectName, parser.getParserID(), source_file, file_size, cal, target + file.getName())); } } }
00
Code Sample 1: public static boolean writeFile(HttpServletResponse resp, File reqFile) { boolean retVal = false; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(reqFile)); IOUtils.copy(in, resp.getOutputStream()); logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath()); } catch (FileNotFoundException e) { logger.error("Resource not found: " + reqFile.getAbsolutePath()); } catch (IOException e) { logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()), e); } finally { IOUtils.closeQuietly(in); } return retVal; } Code Sample 2: public void sendMail() throws Exception { try { if (param.length > 0) { System.setProperty("mail.host", param[0].trim()); URL url = new URL("mailto:" + param[1].trim()); URLConnection conn = url.openConnection(); PrintWriter out = new PrintWriter(conn.getOutputStream(), true); out.print("To:" + param[1].trim() + "\n"); out.print("Subject: " + param[2] + "\n"); out.print("MIME-Version: 1.0\n"); out.print("Content-Type: multipart/mixed; boundary=\"tcppop000\"\n\n"); out.print("--tcppop000\n"); out.print("Content-Type: text/plain\n"); out.print("Content-Transfer-Encoding: 7bit\n\n\n"); out.print(param[3] + "\n\n\n"); out.print("--tcppop000\n"); String filename = param[4].trim(); int sep = filename.lastIndexOf(File.separator); if (sep > 0) { filename = filename.substring(sep + 1, filename.length()); } out.print("Content-Type: text/html; name=\"" + filename + "\"\n"); out.print("Content-Transfer-Encoding: binary\n"); out.print("Content-Disposition: attachment; filename=\"" + filename + "\"\n\n"); System.out.println("FOR ATTACHMENT Content-Transfer-Encoding: binary "); RandomAccessFile file = new RandomAccessFile(param[4].trim(), "r"); byte[] buffer = new byte[(int) file.length()]; file.readFully(buffer); file.close(); String fileContent = new String(buffer); out.print(fileContent); out.print("\n"); out.print("--tcppop000--"); out.close(); } else { } } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } }
11
Code Sample 1: public static boolean copyFile(final File src, final File dst) throws FileNotFoundException { if (src == null || dst == null || src.equals(dst)) { return false; } boolean result = false; if (src.exists()) { if (dst.exists() && !dst.canWrite()) { return false; } final FileInputStream srcStream = new FileInputStream(src); final FileOutputStream dstStream = new FileOutputStream(dst); final FileChannel srcChannel = srcStream.getChannel(); final FileChannel dstChannel = dstStream.getChannel(); FileLock dstLock = null; FileLock srcLock = null; try { srcLock = srcChannel.tryLock(0, Long.MAX_VALUE, true); dstLock = dstChannel.tryLock(); if (srcLock != null && dstLock != null) { int maxCount = 64 * 1024 * 1024 - 32 * 1024; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, maxCount, dstChannel); } } } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } finally { if (srcChannel != null) { try { if (srcLock != null) { srcLock.release(); } srcChannel.close(); srcStream.close(); } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } if (dstChannel != null) { try { if (dstLock != null) { dstLock.release(); } dstChannel.close(); dstStream.close(); result = true; } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } } } return result; } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream target) throws IOException { FileChannel sourceChannel = source.getChannel(); FileChannel targetChannel = target.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.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: public void upgradeSingleFileModelToDirectory(File modelFile) throws IOException { byte[] buf = new byte[8192]; int bytesRead = 0; File backupModelFile = new File(modelFile.getPath() + ".bak"); FileInputStream oldModelIn = new FileInputStream(modelFile); FileOutputStream backupModelOut = new FileOutputStream(backupModelFile); while ((bytesRead = oldModelIn.read(buf)) >= 0) { backupModelOut.write(buf, 0, bytesRead); } backupModelOut.close(); oldModelIn.close(); buf = null; modelFile.delete(); modelFile.mkdir(); BufferedReader oldModelsBuff = new BomStrippingInputStreamReader(new FileInputStream(backupModelFile), "UTF-8"); File metaDataFile = new File(modelFile, ConstantParameters.FILENAMEOFModelMetaData); BufferedWriter metaDataBuff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaDataFile), "UTF-8")); for (int i = 0; i < 8; i++) { metaDataBuff.write(oldModelsBuff.readLine()); metaDataBuff.write('\n'); } metaDataBuff.close(); int classIndex = 1; BufferedWriter modelWriter = null; String line = null; while ((line = oldModelsBuff.readLine()) != null) { if (line.startsWith("Class=") && line.contains("numTraining=") && line.contains("numPos=")) { if (modelWriter != null) { modelWriter.close(); } File nextModel = new File(modelFile, String.format(ConstantParameters.FILENAMEOFPerClassModel, Integer.valueOf(classIndex++))); modelWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(nextModel), "UTF-8")); } modelWriter.write(line); modelWriter.write('\n'); } if (modelWriter != null) { modelWriter.close(); } }
11
Code Sample 1: private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } } Code Sample 2: public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: private ByteBuffer getByteBuffer(String resource) throws IOException { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream in = classLoader.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return ByteBuffer.wrap(out.toByteArray()); }
00
Code Sample 1: public static String calculate(String str) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(str.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException ex) { return null; } } Code Sample 2: @Test public void GetBingSearchResult() throws UnsupportedEncodingException { String query = "Scanner Java example"; String request = "http://api.bing.net/xml.aspx?AppId=731DD1E61BE6DE4601A3008DC7A0EB379149EC29" + "&Version=2.2&Market=en-US&Query=" + URLEncoder.encode(query, "UTF-8") + "&Sources=web+spell&Web.Count=50"; try { URL url = new URL(request); System.out.println("Host : " + url.getHost()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String finalContents = ""; while ((inputLine = reader.readLine()) != null) { finalContents += "\n" + inputLine; } Document doc = Jsoup.parse(finalContents); Elements eles = doc.getElementsByTag("web:Url"); for (Element ele : eles) { System.out.println(ele.text()); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } } 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: public static void writeEntry(File file, File input) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ARGOUML_EXT); temporaryFile.deleteOnExit(); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); FileInputStream inputStream = new FileInputStream(input); ZipEntry entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT); output.putNextEntry(new ZipEntry(entry)); IOUtils.copy(inputStream, output); output.closeEntry(); inputStream.close(); entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + ".argo"); output.putNextEntry(new ZipEntry(entry)); output.write(ArgoWriter.getArgoContent(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT).getBytes()); output.closeEntry(); output.close(); temporaryFile.renameTo(file); } catch (IOException ioe) { throw new PersistenceException(ioe); } } Code Sample 2: private void createProperty(String objectID, String value, String propertyID, Long userID) throws JspTagException { ClassProperty classProperty = new ClassProperty(new Long(propertyID)); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(new Long(propertyID), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: final void saveProject(Project project, final File file) { if (projectsList.contains(project)) { if (project.isDirty() || !file.getParentFile().equals(workspaceDirectory)) { try { if (!file.exists()) { if (!file.createNewFile()) throw new IOException("cannot create file " + file.getAbsolutePath()); } File tmpFile = File.createTempFile("JFPSM", ".tmp"); ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file))); zoStream.setMethod(ZipOutputStream.DEFLATED); ZipEntry projectXMLEntry = new ZipEntry("project.xml"); projectXMLEntry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(projectXMLEntry); CustomXMLEncoder encoder = new CustomXMLEncoder(new BufferedOutputStream(new FileOutputStream(tmpFile))); encoder.writeObject(project); encoder.close(); int bytesIn; byte[] readBuffer = new byte[1024]; FileInputStream fis = new FileInputStream(tmpFile); while ((bytesIn = fis.read(readBuffer)) != -1) zoStream.write(readBuffer, 0, bytesIn); fis.close(); ZipEntry entry; String floorDirectory; for (FloorSet floorSet : project.getLevelSet().getFloorSetsList()) for (Floor floor : floorSet.getFloorsList()) { floorDirectory = "levelset/" + floorSet.getName() + "/" + floor.getName() + "/"; for (MapType type : MapType.values()) { entry = new ZipEntry(floorDirectory + type.getFilename()); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(floor.getMap(type).getImage(), "png", zoStream); } } final String tileDirectory = "tileset/"; for (Tile tile : project.getTileSet().getTilesList()) for (int textureIndex = 0; textureIndex < tile.getMaxTextureCount(); textureIndex++) if (tile.getTexture(textureIndex) != null) { entry = new ZipEntry(tileDirectory + tile.getName() + textureIndex + ".png"); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(tile.getTexture(textureIndex), "png", zoStream); } zoStream.close(); tmpFile.delete(); } catch (IOException ioe) { throw new RuntimeException("The project " + project.getName() + " cannot be saved!", ioe); } } } else throw new IllegalArgumentException("The project " + project.getName() + " is not handled by this project set!"); }
00
Code Sample 1: @MediumTest public void testUrlRewriteRules() throws Exception { ContentResolver resolver = getContext().getContentResolver(); GoogleHttpClient client = new GoogleHttpClient(resolver, "Test", false); Settings.Gservices.putString(resolver, "url:test", "http://foo.bar/ rewrite " + mServerUrl + "new/"); Settings.Gservices.putString(resolver, "digest", mServerUrl); try { HttpGet method = new HttpGet("http://foo.bar/path"); HttpResponse response = client.execute(method); String body = EntityUtils.toString(response.getEntity()); assertEquals("/new/path", body); } finally { client.close(); } } Code Sample 2: public void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
11
Code Sample 1: protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); } Code Sample 2: private static synchronized byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance(algoritmo); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
11
Code Sample 1: @Override public final boolean delete() throws RecordException { if (frozen) { throw new RecordException("The object is frozen."); } Connection conn = ConnectionManager.getConnection(); LoggableStatement pStat = null; Class<? extends Record> actualClass = this.getClass(); StatementBuilder builder = null; try { builder = new StatementBuilder("delete from " + TableNameResolver.getTableName(actualClass) + " where id = :id"); Field f = FieldHandler.findField(this.getClass(), "id"); builder.set("id", FieldHandler.getValue(f, this)); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); return i == 1; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { throw new RecordException("Error executing rollback"); } throw new RecordException(e); } finally { try { if (pStat != null) { pStat.close(); } conn.commit(); conn.close(); } catch (SQLException e) { throw new RecordException("Error closing connection"); } } } Code Sample 2: protected long incrementInDatabase(Object type) { long current_value; long new_value; String entry; if (global_entry != null) entry = global_entry; else throw new UnsupportedOperationException("Named key generators are not yet supported."); String lkw = (String) properties.get("net.ontopia.topicmaps.impl.rdbms.HighLowKeyGenerator.SelectSuffix"); String sql_select; if (lkw == null && (database.equals("sqlserver"))) { sql_select = "select " + valcol + " from " + table + " with (XLOCK) where " + keycol + " = ?"; } else { if (lkw == null) { if (database.equals("sapdb")) lkw = "with lock"; else lkw = "for update"; } sql_select = "select " + valcol + " from " + table + " where " + keycol + " = ? " + lkw; } if (log.isDebugEnabled()) log.debug("KeyGenerator: retrieving: " + sql_select); Connection conn = null; try { conn = connfactory.requestConnection(); PreparedStatement stm1 = conn.prepareStatement(sql_select); try { stm1.setString(1, entry); ResultSet rs = stm1.executeQuery(); if (!rs.next()) throw new OntopiaRuntimeException("HIGH/LOW key generator table '" + table + "' not initialized (no rows)."); current_value = rs.getLong(1); rs.close(); } finally { stm1.close(); } new_value = current_value + grabsize; String sql_update = "update " + table + " set " + valcol + " = ? where " + keycol + " = ?"; if (log.isDebugEnabled()) log.debug("KeyGenerator: incrementing: " + sql_update); PreparedStatement stm2 = conn.prepareStatement(sql_update); try { stm2.setLong(1, new_value); stm2.setString(2, entry); stm2.executeUpdate(); } finally { stm2.close(); } conn.commit(); } catch (SQLException e) { try { if (conn != null) conn.rollback(); } catch (SQLException e2) { } throw new OntopiaRuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { throw new OntopiaRuntimeException(e); } } } value = current_value + 1; max_value = new_value; return value; }
11
Code Sample 1: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); } Code Sample 2: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } }
00
Code Sample 1: public void run() { videoId = videoId.trim(); System.out.println("fetching video"); String requestUrl = "http://www.youtube.com/get_video_info?&video_id=" + videoId; try { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = rd.readLine(); int from = line.indexOf("&token=") + 7; int to = line.indexOf("&thumbnail_url="); String id = line.substring(from, to); String tmp = "http://www.youtube.com/get_video?video_id=" + videoId + "&t=" + id; url = new URL(tmp); conn = (HttpURLConnection) url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); rd.readLine(); tmp = conn.getURL().toString(); url = new URL(tmp); conn = (HttpURLConnection) url.openConnection(); InputStream is; OutputStream outStream; URLConnection uCon; byte[] buf; int ByteRead, ByteWritten = 0; url = new URL(tmp); outStream = new BufferedOutputStream(new FileOutputStream(videoId + ".flv")); uCon = url.openConnection(); is = uCon.getInputStream(); buf = new byte[1024]; while ((ByteRead = is.read(buf)) != -1) { outStream.write(buf, 0, ByteRead); ByteWritten += ByteRead; } is.close(); outStream.close(); System.out.println(videoUrl + " is ready"); } catch (Exception e) { System.out.println("Could not find flv-url " + videoId + "! " + e.getMessage()); } finally { ready = true; } } Code Sample 2: public List<AnalyzerResult> analyze(String urlString, boolean tryFallback) { List<AnalyzerResult> results = new ArrayList<AnalyzerResult>(); try { URL url; if (flow == null) { url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + urlString); } else { url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + urlString); } System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); System.out.println("Executing: " + url.toString()); XMLDecoder decoder = new XMLDecoder(url.openStream()); Map map = (Map) decoder.readObject(); for (Object key : map.keySet()) { results.add(new AnalyzerResult(key.toString(), map.get(key).toString())); } } catch (Exception ex) { ex.printStackTrace(); VueUtil.alert("Can't Execute Flow on the url " + urlString, "Can't Execute Seasr flow"); } return results; }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } 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()))); }
00
Code Sample 1: private static void unpackEntry(File destinationFile, ZipInputStream zin, ZipEntry entry) throws Exception { if (!entry.isDirectory()) { createFolders(destinationFile.getParentFile()); FileOutputStream fis = new FileOutputStream(destinationFile); try { IOUtils.copy(zin, fis); } finally { zin.closeEntry(); fis.close(); } } else { createFolders(destinationFile); } } Code Sample 2: protected void testConnection(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); try { con.connect(); assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); } finally { con.disconnect(); } }
00
Code Sample 1: public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = lst.locationToIndex(e.getPoint()); try { String location = (String) lst.getModel().getElementAt(index), refStr, startStr, stopStr; if (location.indexOf("at chr") != -1) { location = location.substring(location.indexOf("at ") + 3); refStr = location.substring(0, location.indexOf(":")); location = location.substring(location.indexOf(":") + 1); startStr = location.substring(0, location.indexOf("-")); stopStr = location.substring(location.indexOf("-") + 1); moveViewer(refStr, Integer.parseInt(startStr), Integer.parseInt(stopStr)); } else { String hgsid = chooseHGVersion(selPanel.dsn); URL connectURL = new URL("http://genome.ucsc.edu/cgi-bin/hgTracks?hgsid=" + hgsid + "&position=" + location); InputStream urlStream = connectURL.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream)); readUCSCLocation(location, reader); } } catch (Exception exc) { exc.printStackTrace(); } } } Code Sample 2: public void setTypeRefs(Connection conn) { log.traceln("\tProcessing " + table + " references.."); try { String query = " select distinct c.id, c.qualifiedname from " + table + ", CLASSTYPE c " + " where " + table + "." + reffield + " is null and " + table + "." + classnamefield + " = c.qualifiedname"; PreparedStatement pstmt = conn.prepareStatement(query); long start = new Date().getTime(); ResultSet rset = pstmt.executeQuery(); long queryTime = new Date().getTime() - start; log.debug("query time: " + queryTime + " ms"); String update = "update " + table + " set " + reffield + "=? where " + classnamefield + "=? and " + reffield + " is null"; PreparedStatement pstmt2 = conn.prepareStatement(update); int n = 0; start = new Date().getTime(); while (rset.next()) { n++; pstmt2.setInt(1, rset.getInt(1)); pstmt2.setString(2, rset.getString(2)); pstmt2.executeUpdate(); } queryTime = new Date().getTime() - start; log.debug("total update time: " + queryTime + " ms"); log.debug("number of times through loop: " + n); if (n > 0) log.debug("avg update time: " + (queryTime / n) + " ms"); pstmt2.close(); rset.close(); pstmt.close(); conn.commit(); log.verbose("Updated (committed) " + table + " references"); } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }