label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: @Test public void testCopy_readerToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } Code Sample 2: private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
11
Code Sample 1: public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) res += "0" + tmp; else res += tmp; } } catch (NoSuchAlgorithmException ex) { } return res; } Code Sample 2: public void write(PDDocument doc) throws COSVisitorException { document = doc; SecurityHandler securityHandler = document.getSecurityHandler(); if (securityHandler != null) { try { securityHandler.prepareDocumentForEncryption(document); this.willEncrypt = true; } catch (IOException e) { throw new COSVisitorException(e); } catch (CryptographyException e) { throw new COSVisitorException(e); } } else { this.willEncrypt = false; } COSDocument cosDoc = document.getDocument(); COSDictionary trailer = cosDoc.getTrailer(); COSArray idArray = (COSArray) trailer.getDictionaryObject("ID"); if (idArray == null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Long.toString(System.currentTimeMillis()).getBytes()); COSDictionary info = (COSDictionary) trailer.getDictionaryObject("Info"); if (info != null) { Iterator values = info.getValues().iterator(); while (values.hasNext()) { md.update(values.next().toString().getBytes()); } } idArray = new COSArray(); COSString id = new COSString(md.digest()); idArray.add(id); idArray.add(id); trailer.setItem("ID", idArray); } catch (NoSuchAlgorithmException e) { throw new COSVisitorException(e); } } cosDoc.accept(this); }
11
Code Sample 1: public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); } Code Sample 2: private static void copier(FichierElectronique source, FichierElectronique cible) throws IOException { cible.setNom(source.getNom()); cible.setTaille(source.getTaille()); cible.setTypeMime(source.getTypeMime()); cible.setSoumetteur(source.getSoumetteur()); cible.setDateDerniereModification(source.getDateDerniereModification()); cible.setEmprunteur(source.getEmprunteur()); cible.setDateEmprunt(source.getDateEmprunt()); cible.setNumeroVersion(source.getNumeroVersion()); InputStream inputStream = source.getInputStream(); OutputStream outputStream = cible.getOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { try { inputStream.close(); } finally { outputStream.close(); } if (source instanceof FichierElectroniqueDefaut) { FichierElectroniqueDefaut fichierElectroniqueTemporaire = (FichierElectroniqueDefaut) source; fichierElectroniqueTemporaire.deleteTemp(); } } }
00
Code Sample 1: private static byte[] loadBytecodePrivileged() { URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz"); try { InputStream in = url.openStream(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (; ; ) { int r = in.read(); if (r == -1) { return bout.toByteArray(); } bout.write(r); } } finally { in.close(); } } catch (IOException e) { throw new UndeclaredThrowableException(e); } } Code Sample 2: private void reloadData(String dataSourceUrl) { try { URL url = new URL(dataSourceUrl); InputStream is = url.openStream(); if (progressMonitor.isCanceled() == false) { progressMonitor.setNote("Building classifications..."); progressMonitor.setProgress(2); mediator.loadClassificationTree(is); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static String hashValue(String password, String salt) throws TeqloException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); md.update(salt.getBytes("UTF-8")); byte raw[] = md.digest(); char[] encoded = (new BASE64Encoder()).encode(raw).toCharArray(); int length = encoded.length; while (length > 0 && encoded[length - 1] == '=') length--; for (int i = 0; i < length; i++) { if (encoded[i] == '+') encoded[i] = '*'; else if (encoded[i] == '/') encoded[i] = '-'; } return new String(encoded, 0, length); } catch (Exception e) { throw new TeqloException("Security", "password", e, "Could not process password"); } } Code Sample 2: public static String getDigest(String input) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(input.getBytes()); byte[] outDigest = md5.digest(); StringBuffer outBuf = new StringBuffer(33); for (int i = 0; i < outDigest.length; i++) { byte b = outDigest[i]; int hi = (b >> 4) & 0x0f; outBuf.append(MD5Digest.hexTab[hi]); int lo = b & 0x0f; outBuf.append(MD5Digest.hexTab[lo]); } return outBuf.toString(); }
11
Code Sample 1: public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } } Code Sample 2: @Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
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 displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: public void testManageSources() throws Exception { this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); final File implementationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); final File specificationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("IllegalImplementationSource.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); IOUtils.copy(this.getClass().getResourceAsStream("IllegalSpecificationSource.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); try { this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } try { this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } this.getTestTool().setProfile("DOES_NOT_EXIST"); this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), this.getTestSourcesDirectory()); } Code Sample 2: private byte[] getBytes(String resource) throws IOException { InputStream is = HttpServletFileDownloadTest.class.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); IOUtils.closeQuietly(is); return out.toByteArray(); }
00
Code Sample 1: private String fetchHTML(String s) { String str; StringBuffer sb = new StringBuffer(); try { URL url = new URL(s); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((str = br.readLine()) != null) { sb.append(str); } } catch (MalformedURLException e) { } catch (IOException e) { } return sb.toString(); } Code Sample 2: public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map templateContext, CmsOFBizRemoteClient remoteClient, Writer out, boolean cache) throws IOException, GeneralException { Map context = (Map) templateContext.get("context"); if (context == null) { context = FastMap.newInstance(); } String webSiteId = (String) templateContext.get("webSiteId"); if (UtilValidate.isEmpty(webSiteId)) { if (context != null) webSiteId = (String) context.get("webSiteId"); } String https = (String) templateContext.get("https"); if (UtilValidate.isEmpty(https)) { if (context != null) https = (String) context.get("https"); } Map fields = dataResource.getAllFields(); String dataResourceId = (String) fields.get("dataResourceId"); String dataResourceTypeId = (String) fields.get("dataResourceTypeId"); if (UtilValidate.isEmpty(dataResourceTypeId)) { dataResourceTypeId = "SHORT_TEXT"; } if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) { String text = (String) fields.get("objectInfo"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) { GenericValue electronicText; if (cache) { electronicText = remoteClient.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } else { electronicText = remoteClient.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } fields = electronicText.getAllFields(); String text = (String) fields.get("textData"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_OBJECT")) { String text = (String) fields.get("dataResourceId"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.equals("URL_RESOURCE")) { String text = null; URL url = new URL((String) fields.get("objectInfo")); if (url.getHost() != null) { InputStream in = url.openStream(); int c; StringWriter sw = new StringWriter(); while ((c = in.read()) != -1) { sw.write(c); } sw.close(); text = sw.toString(); } else { String prefix = DataResourceWorker.buildRequestPrefix(remoteClient, locale, webSiteId, https); String sep = ""; if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { sep = "/"; } String fixedUrlStr = prefix + sep + url.toString(); URL fixedUrl = new URL(fixedUrlStr); text = (String) fixedUrl.getContent(); } out.write(text); } else if (dataResourceTypeId.endsWith("_FILE_BIN")) { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_FILE")) { String dataResourceMimeTypeId = (String) fields.get("mimeTypeId"); String objectInfo = (String) fields.get("objectInfo"); String rootDir = (String) context.get("rootDir"); if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) { renderFile(dataResourceTypeId, objectInfo, rootDir, out); } else { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } } else { throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText"); } }
00
Code Sample 1: @Override public void run() { HttpGet httpGet = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); DataModel model = DataModel.getInstance(); for (City city : citiesToBeUpdated) { String preferredUnitType = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.settings_units_key), context.getString(R.string.settings_units_default_value)); String codePrefix = city.getCountryName().startsWith("United States") ? GET_PARAM_ZIP_PREFIX : GET_PARAM_CITY_CODE_PREFIX; String requestUri = new String(GET_URL + "?" + GET_PARAM_ACODE_PREFIX + "=" + GET_PARAM_ACODE + "&" + codePrefix + "=" + city.getId() + "&" + GET_PARAM_UNIT_PREFIX + "=" + preferredUnitType); httpGet = new HttpGet(requestUri); HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { processXML(response.getEntity().getContent()); for (ForecastedDay day : forecast) { int pos = day.getImageURL().lastIndexOf('/'); if (pos < 0 || pos + 1 == day.getImageURL().length()) throw new Exception("Invalid image URL"); final String imageFilename = day.getImageURL().substring(pos + 1); File downloadDir = context.getDir(ForecastedDay.DOWNLOAD_DIR, Context.MODE_PRIVATE); File[] imagesFilteredByName = downloadDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.equals(imageFilename)) return true; else return false; } }); if (imagesFilteredByName.length == 0) { httpGet = new HttpGet(day.getImageURL()); response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedOutputStream bus = null; try { bus = new BufferedOutputStream(new FileOutputStream(downloadDir.getAbsolutePath() + "/" + imageFilename)); response.getEntity().writeTo(bus); } finally { bus.close(); } } } } city.setDays(forecast); city.setLastUpdated(Calendar.getInstance().getTime()); model.saveCity(city); } } } catch (Exception e) { httpGet.abort(); e.printStackTrace(); } finally { handler.sendEmptyMessage(1); } } Code Sample 2: public static Image getPluginImage(final Object plugin, final String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
11
Code Sample 1: public static void copyFile(File src, File dest) { try { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.err.println(ioe); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private 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 void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void read(Model m, String url) throws JenaException { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) read(m, conn.getInputStream(), url); else read(m, new InputStreamReader(conn.getInputStream(), encoding), url); } catch (FileNotFoundException e) { throw new DoesNotExistException(url); } catch (IOException e) { throw new JenaException(e); } } Code Sample 2: private static String getUnsaltedHash(String algorithm, String input) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.reset(); messageDigest.update(input.getBytes(Main.DEFAULT_CHARSET)); byte[] digest = messageDigest.digest(); return String.format(Main.DEFAULT_LOCALE, "%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); }
00
Code Sample 1: protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient f = new FTPClient(); f.connect(fpi.getHost()); f.login(fpi.getUsername(), fpi.getPassword()); return f; } Code Sample 2: private void writeCard() { try { new URL(createURLStringExistRESTGetXQuery("update value //scheda[cata = \"" + cata + "\"] with " + "\"replaced from /schede/scheda-... by jEpi-Scheda-Applet\"")).openStream().close(); String urlString = "http://" + server + "/exist/rest/db/schede/" + "scheda-" + cata + ".xml"; HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(urlString).openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("PUT"); OutputStream outputStream = httpURLConnection.getOutputStream(); uiSchedaXml.write(outputStream); outputStream.close(); httpURLConnection.getInputStream().close(); httpURLConnection.disconnect(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } }
11
Code Sample 1: static String hash(String text) { try { StringBuffer plugins = new StringBuffer(); for (PlayPlugin plugin : Play.plugins) { plugins.append(plugin.getClass().getName()); } MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update((Play.version + plugins.toString() + text).getBytes("utf-8")); byte[] digest = messageDigest.digest(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { int value = digest[i]; if (value < 0) { value += 256; } builder.append(Integer.toHexString(value)); } return builder.toString(); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public boolean check(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(realm.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(password.getBytes("ISO-8859-1")); byte[] ha1 = md.digest(); String hexHa1 = new String(Hex.encodeHex(ha1)); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); String hexHa2 = new String(Hex.encodeHex(ha2)); md.reset(); md.update(hexHa1.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nc.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(cnonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(qop.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(hexHa2.getBytes("ISO-8859-1")); byte[] digest = md.digest(); String hexDigest = new String(Hex.encodeHex(digest)); return (hexDigest.equalsIgnoreCase(response)); }
00
Code Sample 1: public void appendFetch(IProgress progress, PrintWriter pw, String list, int from, int to) throws IOException { progress.start(); try { File storage = new File(cacheDirectory.getValue(), "mboxes"); storage.mkdirs(); File mbox = new File(storage, list + "-" + from + "-" + to + ".mbox"); if (mbox.exists()) { BufferedReader in = new BufferedReader(new InputStreamReader(new ProgressInputStream(new FileInputStream(mbox), progress, 10000))); String line; while ((line = in.readLine()) != null) { pw.write(line); pw.write('\n'); } in.close(); return; } progress.setScale(100); IProgress subProgress1 = progress.getSub(75); URL url = getGmaneURL(list, from, to); BufferedReader in = new BufferedReader(new InputStreamReader(new ProgressInputStream(url.openStream(), subProgress1, 10000))); PrintWriter writeToMbox = new PrintWriter(mbox); int lines = 0; String line; while ((line = in.readLine()) != null) { lines++; if (line.matches("^From .*$") && !line.matches("^From .*? .*[0-9][0-9]:[0-9][0-9]:[0-9][0-9].*$")) { line = ">" + line; } writeToMbox.write(line); writeToMbox.write('\n'); } in.close(); writeToMbox.close(); appendFetch(progress.getSub(25), pw, list, from, to); } finally { progress.done(); } } Code Sample 2: public final String hashRealmPassword(String username, String realm, String password) throws GeneralSecurityException { MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] hash = md.digest(); return toHex(hash, hash.length); }
00
Code Sample 1: private InputStream urlToInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", IE); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); String encoding = conn.getContentEncoding(); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) return new GZIPInputStream(conn.getInputStream()); else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else return conn.getInputStream(); } Code Sample 2: public HSSFWorkbook callRules(URL urlOfExcelDataFile, RuleSource ruleSource, String excelLogSheet) throws DroolsParserException, IOException, ClassNotFoundException { InputStream inputFromExcel = null; try { log.info("Looking for url:" + urlOfExcelDataFile); inputFromExcel = urlOfExcelDataFile.openStream(); log.info("found url:" + urlOfExcelDataFile); } catch (MalformedURLException e) { log.log(Level.SEVERE, "Malformed URL Exception Loading rules", e); throw e; } catch (IOException e) { log.log(Level.SEVERE, "IO Exception Loading rules", e); throw e; } return callRules(inputFromExcel, ruleSource, excelLogSheet); }
11
Code Sample 1: protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } } Code Sample 2: public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public boolean actualizarIdPartida(int idJugadorDiv, int idRonda, int idPartida) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public int delete(BusinessObject o) throws DAOException { int delete = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_BILL")); pst.setInt(1, bill.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
00
Code Sample 1: 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; } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(sourceFile); os = new FileOutputStream(destFile); IOUtils.copy(is, os); } finally { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType(req.getContentType()); IOUtils.copy(req.getReader(), resp.getWriter()); } Code Sample 2: public void install(Session session) throws Exception { String cfgPath = ConfigurationFactory.getConfigSonInstance().getConfigurationPath(); File setupKson = new File(cfgPath, "setup.kson"); InputStream is = null; if (setupKson.exists()) { log.debug("Reagind kson from " + setupKson.getAbsolutePath()); is = new FileInputStream(setupKson); } else { String ksonCp = "/org/chon/cms/core/setup/setup.kson"; is = Setup.class.getResourceAsStream(ksonCp); log.info("Creating initial setup.kson in " + setupKson.getAbsolutePath()); IOUtils.copy(is, new FileOutputStream(setupKson)); is = new FileInputStream(setupKson); } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; lines.add(line); } List<NodeCreation> ncList = readKSon(lines.toArray(new String[lines.size()])); for (NodeCreation nc : ncList) { try { createNode(session, nc); } catch (Exception e) { System.err.println("error crating node " + nc.path + " -> " + e.getMessage()); } } session.save(); }
00
Code Sample 1: @Override public InputStream getStream(String uri) throws IOException { debug.print("uri=" + uri); boolean isStreamFile = false; for (int i = 0; i < GLOBAL.extList.length; i++) { if (uri.toLowerCase().endsWith(GLOBAL.extList[i].toLowerCase())) { isStreamFile = true; } } if (isStreamFile) { GLOBAL.streamFile = DIR + File.separator + uri; File file = new File(GLOBAL.streamFile); URL url = file.toURI().toURL(); System.out.println("url=" + url); GLOBAL.cstream = new CountInputStream(url.openStream()); if (GLOBAL.Resume && GLOBAL.positions.containsKey(GLOBAL.streamFile)) { GLOBAL.Resume = false; if (uri.toLowerCase().endsWith(".mpg") || uri.toLowerCase().endsWith(".vob") || uri.toLowerCase().endsWith(".mp2") || uri.toLowerCase().endsWith(".mpeg") || uri.toLowerCase().endsWith(".mpeg2")) { System.out.println("--Skipping to last bookmark=" + GLOBAL.positions.get(GLOBAL.streamFile)); GLOBAL.cstream.skip(GLOBAL.positions.get(GLOBAL.streamFile)); } } return GLOBAL.cstream; } return super.getStream(uri); } Code Sample 2: public void includeJs(Group group, Writer out, PageContext pageContext) throws IOException { includeResource(pageContext, out, RetentionHelper.buildRootRetentionFilePath(group, ".js"), JS_BEGIN_TAG, JS_END_TAG); ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".js"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); fileStream.close(); } }
11
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: @NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; } Code Sample 2: protected String encrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PublicKey pk = getPublicKey(key); if (pk == null) { throw new CryptographicFailureException("PublicKeyNotFound", String.format("Cannot find public key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(data.getBytes()); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(Base64.encodeBase64(bout.toByteArray())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
11
Code Sample 1: public static String getMD5(String s) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(s.getBytes()); byte[] result = md5.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < result.length; i++) { hexString.append(String.format("%02x", 0xFF & result[i])); } return hexString.toString(); } Code Sample 2: public static String md5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(value.getBytes()); return bytesToString(messageDigest.digest()); } catch (Exception ex) { Tools.logException(Tools.class, ex, value); } return value; }
00
Code Sample 1: public static String getResourceFromURL(URL url, String acceptHeader) throws java.io.IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Accept", acceptHeader); urlConnection.setInstanceFollowRedirects(true); BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String content = ""; String line; while ((line = input.readLine()) != null) { content += line; } input.close(); return content; } Code Sample 2: private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); }
00
Code Sample 1: public static 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) { } } } } Code Sample 2: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
00
Code Sample 1: private void setupPool() { this.pool = new ObjectPool(this.numConns) { protected Object getNewObject() throws IOException { URLConnection conn = HTTPMessageDeliveryImpl.this.url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "text/xml"); return conn; } }; } Code Sample 2: public static String base64HashedString(String v) { String base64HashedPassword = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(v.getBytes()); String hashedPassword = new String(md.digest()); sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); base64HashedPassword = enc.encode(hashedPassword.getBytes()); } catch (java.security.NoSuchAlgorithmException e) { throw new NSForwardException(e, "Couldn't find the SHA hash algorithm; perhaps you do not have the SunJCE security provider installed properly?"); } return base64HashedPassword; }
00
Code Sample 1: @Override public void run() { try { bitmapDrawable = new BitmapDrawable(new URL(url).openStream()); imageCache.put(id, new SoftReference<Drawable>(bitmapDrawable)); log("image::: put: id = " + id + " "); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } handler.post(new Runnable() { @Override public void run() { iv.setImageDrawable(bitmapDrawable); } }); } Code Sample 2: public String output(final ComponentParameter compParameter) { InputStream inputStream; try { final URL url = new URL("http://xml.weather.yahoo.com/forecastrss?p=" + getPagelet().getOptionProperty("_weather_code") + "&u=c"); inputStream = url.openStream(); } catch (final IOException e) { return e.getMessage(); } final StringBuilder sb = new StringBuilder(); new AbstractXmlDocument(inputStream) { @Override protected void init() throws Exception { final Element root = getRoot(); final Namespace ns = root.getNamespaceForPrefix("yweather"); final Element channel = root.element("channel"); final String link = channel.elementText("link"); final Element item = channel.element("item"); Element ele = item.element(QName.get("condition", ns)); if (ele == null) { sb.append("ERROR"); return; } final String imgPath = getPagelet().getColumnBean().getPortalBean().getCssResourceHomePath(compParameter) + "/images/yahoo/"; String text, image; Date date = new SimpleDateFormat(YahooWeatherUtils.RFC822_MASKS[1], Locale.US).parse(ele.attributeValue("date")); final int temp = Integer.parseInt(ele.attributeValue("temp")); int code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append("<div style=\"line-height: normal;\"><a target=\"_blank\" href=\"").append(link).append("\"><img src=\""); sb.append(image).append("\" /></a>"); sb.append(YahooWeatherUtils.formatHour(date)).append(" - "); sb.append(text).append(" - ").append(temp).append("℃").append("<br>"); final Iterator<?> it = item.elementIterator(QName.get("forecast", ns)); while (it.hasNext()) { ele = (Element) it.next(); date = new SimpleDateFormat("dd MMM yyyy", Locale.US).parse(ele.attributeValue("date")); final int low = Integer.parseInt(ele.attributeValue("low")); final int high = Integer.parseInt(ele.attributeValue("high")); code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append(YahooWeatherUtils.formatWeek(date)).append(" ( "); sb.append(text).append(". "); sb.append(low).append("℃~").append(high).append("℃"); sb.append(" )<br>"); } sb.append("</div>"); } }; return sb.toString(); }
11
Code Sample 1: public static void DecodeMapFile(String mapFile, String outputFile) throws Exception { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; InputStream map; OutputStream output; try { map = new FileInputStream(mapFile); } catch (Exception e) { throw new Exception("Map file error", e); } try { output = new FileOutputStream(outputFile); } catch (Exception e) { throw new Exception("Map file error", e); } while ((nread = map.read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.write(buffer, 0, nread); } map.close(); output.close(); } 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: private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException { File pathToWebInf = new File(portletDir, "WEB-INF"); File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf); tempWebXml.deleteOnExit(); OutputStream webOutputStream = new FileOutputStream(tempWebXml); PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY; IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream); webOutputStream.close(); return tempWebXml; } Code Sample 2: private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } }
11
Code Sample 1: public void downloadFile(OutputStream os, int fileId) throws IOException, SQLException { Connection conn = null; try { conn = ds.getConnection(); Guard.checkConnectionNotNull(conn); PreparedStatement ps = conn.prepareStatement("select * from FILE_BODIES where file_id=?"); ps.setInt(1, fileId); ResultSet rs = ps.executeQuery(); if (!rs.next()) { throw new FileNotFoundException("File with id=" + fileId + " not found!"); } Blob blob = rs.getBlob("data"); InputStream is = blob.getBinaryStream(); IOUtils.copyLarge(is, os); } finally { JdbcDaoHelper.safeClose(conn, log); } } Code Sample 2: 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); } }
00
Code Sample 1: public void testStreamURL() throws Exception { boolean ok = false; String url = "http://www.apache.org/dist/lucene/solr/"; String txt = null; try { txt = IOUtils.toString(new URL(url).openStream()); } catch (Exception ex) { fail("this test only works if you have a network connection."); return; } SolrCore core = h.getCore(); Map<String, String[]> args = new HashMap<String, String[]>(); args.put(CommonParams.STREAM_URL, new String[] { url }); List<ContentStream> streams = new ArrayList<ContentStream>(); parser.buildRequestFrom(core, new MultiMapSolrParams(args), streams); assertEquals(1, streams.size()); assertEquals(txt, IOUtils.toString(streams.get(0).getStream())); } Code Sample 2: @NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; }
00
Code Sample 1: public void generateListOfSubscriptions() { try { java.net.URL url = new java.net.URL(NewGenLibDesktopRoot.getInstance().getURLRoot() + "/NEWGEN_JR/ListOfSubscriptions.xml"); System.out.println(NewGenLibDesktopRoot.getRoot() + "/NEWGEN_JR/ListOfSubscriptions.xml"); net.sf.jasperreports.engine.design.JasperDesign jd = net.sf.jasperreports.engine.xml.JRXmlLoader.load(url.openStream()); System.out.println("in generate Report 30" + dtm.getRowCount()); net.sf.jasperreports.engine.JasperReport jr = net.sf.jasperreports.engine.JasperCompileManager.compileReport(jd); System.out.println("in generate Report 32" + dtm.getRowCount()); java.util.Map param = new java.util.HashMap(); param.put("ReportTitle", "List of subscriptions"); Class.forName("org.postgresql.Driver"); System.out.println("in generate Report 37" + dtm.getRowCount()); net.sf.jasperreports.engine.JasperPrint jp = net.sf.jasperreports.engine.JasperFillManager.fillReport(jr, param, new net.sf.jasperreports.engine.data.JRTableModelDataSource(dtm)); System.out.println("in generate Report 39" + dtm.getRowCount()); java.sql.Timestamp currentTime = new java.sql.Timestamp(java.util.Calendar.getInstance().getTimeInMillis()); if (jp.getPages().size() != 0) net.sf.jasperreports.view.JasperViewer.viewReport(jp, false); else javax.swing.JOptionPane.showMessageDialog(reports.DeskTopFrame.getInstance(), "There are no records in the selected report option."); System.out.println("in generate Report 43" + dtm.getRowCount()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
00
Code Sample 1: @Test public void test02_ok_200_logo() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(xlsURL); HttpResponse response = client.execute(post); assertEquals("failed code for ", 200, response.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } } Code Sample 2: public static void main(String[] args) throws IOException { PostParameter a1 = new PostParameter("v", Utils.encode("1.0")); PostParameter a2 = new PostParameter("api_key", Utils.encode(RenRenConstant.apiKey)); PostParameter a3 = new PostParameter("method", Utils.encode("notifications.send")); PostParameter a4 = new PostParameter("call_id", System.nanoTime()); PostParameter a5 = new PostParameter("session_key", Utils.encode("5.22af9ee9ad842c7eb52004ece6e96b10.86400.1298646000-350727914")); PostParameter a6 = new PostParameter("to_ids", Utils.encode("350727914")); PostParameter a7 = new PostParameter("notification", "又到了要睡觉的时间了。"); PostParameter a8 = new PostParameter("format", Utils.encode("JSON")); RenRenPostParameters ps = new RenRenPostParameters(Utils.encode(RenRenConstant.secret)); ps.addParameter(a1); ps.addParameter(a2); ps.addParameter(a3); ps.addParameter(a4); ps.addParameter(a5); ps.addParameter(a6); ps.addParameter(a7); ps.addParameter(a8); System.out.println(RenRenConstant.apiUrl + "?" + ps.generateUrl()); URL url = new URL(RenRenConstant.apiUrl + "?" + ps.generateUrl()); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput(true); request.setRequestMethod("POST"); System.out.println("Sending request..."); request.connect(); System.out.println("Response: " + request.getResponseCode() + " " + request.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String b = null; while ((b = reader.readLine()) != null) { System.out.println(b); } }
11
Code Sample 1: private String hashmd5(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; } Code Sample 2: public String md5sum(String toCompute) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toCompute.getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); }
00
Code Sample 1: public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public static String md5Encode(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return s; } }
00
Code Sample 1: public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException { log.debug("copyLocalFileAsTempFileInExternallyAccessableDir"); File f = this.createTempFileInExternallyAccessableDir(); FileChannel srcChannel = new FileInputStream(localFileRef).getChannel(); FileChannel dstChannel = new FileOutputStream(f).getChannel(); log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef + " to dest-outputStream: " + f.getAbsolutePath()); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath()); return f; } Code Sample 2: public static Map getFile(DispatchContext dctx, Map context) { String localFilename = (String) context.get("localFilename"); OutputStream localFile = null; try { localFile = new FileOutputStream(localFilename); } catch (IOException ioe) { Debug.logError(ioe, "[getFile] Problem opening local file", module); return ServiceUtil.returnError("ERROR: Could not open local file"); } List errorList = new ArrayList(); FTPClient ftp = new FTPClient(); try { ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { errorList.add("Server refused connection"); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); if (!ftp.login(username, password)) { errorList.add("Login failed (" + username + ", " + password + ")"); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) { errorList.add("File not received succesfully: " + ftp.getReplyString()); } } ftp.logout(); } } catch (IOException ioe) { errorList.add("Problem with FTP transfer: " + ioe.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException dce) { Debug.logWarning(dce, "[getFile] Problem with FTP disconnect", module); } } } try { localFile.close(); } catch (IOException ce) { Debug.logWarning(ce, "[getFile] Problem closing local file", module); } if (errorList.size() > 0) { Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } return ServiceUtil.returnSuccess(); }
11
Code Sample 1: public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } } Code Sample 2: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, 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: private synchronized Document executeHttpMethod(final HttpUriRequest httpRequest) throws UnauthorizedException, ThrottledException, ApiException { if (!isNextRequestAllowed()) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Wait " + WAITING_TIME + "ms for request."); } wait(WAITING_TIME); } catch (InterruptedException ie) { throw new ApiException("Waiting for request interrupted.", ie); } } try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Perform request."); } HttpResponse httpResponse = httpClient.execute(httpRequest); switch(httpResponse.getStatusLine().getStatusCode()) { case HTTP_OK: HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream responseStream = httpEntity.getContent(); if (responseStream == null) { throw new ApiException("TODO"); } else { String response = null; try { response = IOUtils.toString(responseStream, RESPONSE_ENCODING); } catch (IOException ioe) { throw new ApiException("Problem reading response", ioe); } catch (RuntimeException re) { httpRequest.abort(); throw new ApiException("Problem reading response", re); } finally { responseStream.close(); } StringReader responseReader = new StringReader(response); Document document = documentBuilder.parse(new InputSource(responseReader)); return document; } } case HTTP_UNAVAILABLE: throw new ThrottledException("TODO"); case HTTP_UNAUTHORIZED: throw new UnauthorizedException("TODO"); default: throw new ApiException("Unexpected HTTP status code: " + httpResponse.getStatusLine().getStatusCode()); } } catch (SAXException se) { throw new ApiException("TODO", se); } catch (IOException ioe) { throw new ApiException("TODO", ioe); } finally { updateLastRequestTimestamp(); } }
11
Code Sample 1: public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static File copyFile(File fileToCopy, File copiedFile) { BufferedInputStream in = null; BufferedOutputStream outWriter = null; if (!copiedFile.exists()) { try { copiedFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } } try { in = new BufferedInputStream(new FileInputStream(fileToCopy), 4096); outWriter = new BufferedOutputStream(new FileOutputStream(copiedFile), 4096); int c; while ((c = in.read()) != -1) outWriter.write(c); in.close(); outWriter.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } return copiedFile; }
11
Code Sample 1: private void initFtp() throws IOException { ftpClient.setConnectTimeout(5000); ftpClient.connect(ftpHost); ftpClient.login(userName, password); if (workingDir != null) { ftpClient.changeWorkingDirectory(workingDir); } logger.info("Connection established."); } Code Sample 2: protected static void createBackup() throws IOException, IllegalStateException, FTPIllegalReplyException, FTPException, FileNotFoundException, FTPDataTransferException, FTPAbortedException { String cmd = "mysqldump -u " + Constants.dbUser + " -p" + Constants.dbPassword + " " + Constants.dbName + " > " + Constants.tmpDir + "Backup.sql"; FileWriter fstream = new FileWriter(Constants.tmpDir + Constants.tmpScript); BufferedWriter out = new BufferedWriter(fstream); out.write(cmd); out.close(); Process process = Runtime.getRuntime().exec(Constants.tmpDir + Constants.tmpScript); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (br.readLine() != null) { ; } String fileName = now4backup(); cmd = "\"C:\\Archivos de programa\\WinRAR\\Rar.exe\" a -m5 -ed " + Constants.tmpDir + fileName + " " + Constants.tmpDir + "Backup.sql"; process = Runtime.getRuntime().exec(cmd); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while (br.readLine() != null) { ; } FTPClient client = new FTPClient(); client.connect(Constants.ftpBackupAddr); client.login(Constants.ftpBackupUser, Constants.ftpBackupPassword); client.changeDirectory("/" + Shared.getConfig("storeName")); File f = new File(Constants.tmpDir + fileName); client.upload(f); client.disconnect(false); }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } } Code Sample 2: public boolean backupFile(File oldFile, File newFile) { boolean isBkupFileOK = false; FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(oldFile).getChannel(); targetChannel = new FileOutputStream(newFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying config file", e); } finally { if ((newFile != null) && (newFile.exists()) && (newFile.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.log(Level.INFO, "closing channels failed"); } } return isBkupFileOK; }
00
Code Sample 1: protected PredicateAnnotationRecord generatePredicateAnnotationRecord(PredicateAnnotationRecord par, String miDescriptor) { String annotClass = par.annotation.getType().substring(1, par.annotation.getType().length() - 1).replace('/', '.'); String methodName = getMethodName(par); String hashKey = annotClass + CLASS_SIG_SEPARATOR_STRING + methodName; PredicateAnnotationRecord gr = _generatedPredicateRecords.get(hashKey); if (gr != null) { _sharedAddData.cacheInfo.incCombinePredicateCacheHit(); return gr; } else { _sharedAddData.cacheInfo.incCombinePredicateCacheMiss(); } String predicateClass = ((_predicatePackage.length() > 0) ? (_predicatePackage + ".") : "") + annotClass + "Pred"; ClassFile predicateCF = null; File clonedFile = new File(_predicatePackageDir, annotClass.replace('.', '/') + "Pred.class"); if (clonedFile.exists() && clonedFile.isFile() && clonedFile.canRead()) { try { predicateCF = new ClassFile(new FileInputStream(clonedFile)); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate class file, source=" + clonedFile, ioe); } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { _templatePredicateClassFile.write(baos); predicateCF = new ClassFile(new ByteArrayInputStream(baos.toByteArray())); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate template class file", ioe); } } clonedFile.getParentFile().mkdirs(); final ArrayList<String> paramNames = new ArrayList<String>(); final HashMap<String, String> paramTypes = new HashMap<String, String>(); performCombineTreeWalk(par, new ILambda.Ternary<Object, String, String, AAnnotationsAttributeInfo.Annotation.AMemberValue>() { public Object apply(String param1, String param2, AAnnotationsAttributeInfo.Annotation.AMemberValue param3) { paramNames.add(param1); paramTypes.put(param1, param2); return null; } }, ""); ArrayList<PredicateAnnotationRecord> memberPARs = new ArrayList<PredicateAnnotationRecord>(); for (String key : par.combinedPredicates.keySet()) { for (PredicateAnnotationRecord memberPAR : par.combinedPredicates.get(key)) { if ((memberPAR.predicateClass != null) && (memberPAR.predicateMI != null)) { memberPARs.add(memberPAR); } else { memberPARs.add(generatePredicateAnnotationRecord(memberPAR, miDescriptor)); } } } AUTFPoolInfo predicateClassNameItem = new ASCIIPoolInfo(predicateClass.replace('.', '/'), predicateCF.getConstantPool()); int[] l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassNameItem }); predicateClassNameItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ClassPoolInfo predicateClassItem = new ClassPoolInfo(predicateClassNameItem, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassItem }); predicateClassItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckClassVisitor.singleton(), null); predicateCF.setThisClass(predicateClassItem); StringBuilder sb = new StringBuilder(); sb.append("(Ljava/lang/Object;"); if (par.passArguments) { sb.append("[Ljava/lang/Object;"); } for (String key : paramNames) { sb.append(paramTypes.get(key)); } sb.append(")Z"); String methodDesc = sb.toString(); MethodInfo templateMI = null; MethodInfo predicateMI = null; for (MethodInfo mi : predicateCF.getMethods()) { if ((mi.getName().toString().equals(methodName)) && (mi.getDescriptor().toString().equals(methodDesc))) { predicateMI = mi; break; } else if ((mi.getName().toString().equals("template")) && (mi.getDescriptor().toString().startsWith("(")) && (mi.getDescriptor().toString().endsWith(")Z"))) { templateMI = mi; } } if ((templateMI == null) && (predicateMI == null)) { throw new ThreadCheckException("Could not find template predicate method in class file"); } if (predicateMI == null) { AUTFPoolInfo namecpi = new ASCIIPoolInfo(methodName, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { namecpi }); namecpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); AUTFPoolInfo descpi = new ASCIIPoolInfo(methodDesc, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { descpi }); descpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ArrayList<AAttributeInfo> list = new ArrayList<AAttributeInfo>(); for (AAttributeInfo a : templateMI.getAttributes()) { try { AAttributeInfo clonedA = (AAttributeInfo) a.clone(); list.add(clonedA); } catch (CloneNotSupportedException e) { throw new InstrumentorException("Could not clone method attributes"); } } predicateMI = new MethodInfo(templateMI.getAccessFlags(), namecpi, descpi, list.toArray(new AAttributeInfo[] {})); predicateCF.getMethods().add(predicateMI); CodeAttributeInfo.CodeProperties props = predicateMI.getCodeAttributeInfo().getProperties(); props.maxLocals += paramTypes.size() + 1 + (par.passArguments ? 1 : 0); InstructionList il = new InstructionList(predicateMI.getCodeAttributeInfo().getCode()); if ((par.combineMode == Combine.Mode.OR) || (par.combineMode == Combine.Mode.XOR) || (par.combineMode == Combine.Mode.IMPLIES)) { il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); } else { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); } boolean res; res = il.advanceIndex(); assert res == true; int accumVarIndex = props.maxLocals - 1; AInstruction loadAccumInstr; AInstruction storeAccumInstr; if (accumVarIndex < 256) { loadAccumInstr = new GenericInstruction(Opcode.ILOAD, (byte) accumVarIndex); storeAccumInstr = new GenericInstruction(Opcode.ISTORE, (byte) accumVarIndex); } else { byte[] bytes = new byte[] { Opcode.ILOAD, 0, 0 }; Types.bytesFromShort((short) accumVarIndex, bytes, 1); loadAccumInstr = new WideInstruction(bytes); bytes[0] = Opcode.ISTORE; storeAccumInstr = new WideInstruction(bytes); } il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int maxStack = 0; int paramIndex = 1; int lvIndex = 1; if (par.passArguments) { lvIndex += 1; } int memberCount = 0; for (PredicateAnnotationRecord memberPAR : memberPARs) { ++memberCount; il.insertInstr(new GenericInstruction(Opcode.ALOAD_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int curStack = 1; if (memberPAR.passArguments) { if (par.passArguments) { il.insertInstr(new GenericInstruction(Opcode.ALOAD_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; curStack += 1; } } for (int paramNameIndex = 0; paramNameIndex < memberPAR.paramNames.size(); ++paramNameIndex) { String t = memberPAR.paramTypes.get(memberPAR.paramNames.get(paramNameIndex)); if (t.length() == 0) { throw new ThreadCheckException("Length of parameter type no. " + paramIndex + " string is 0 in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } byte opcode; int nextLVIndex = lvIndex; switch(t.charAt(0)) { case 'I': case 'B': case 'C': case 'S': case 'Z': opcode = Opcode.ILOAD; nextLVIndex += 1; curStack += 1; break; case 'F': opcode = Opcode.FLOAD; nextLVIndex += 1; curStack += 1; break; case '[': case 'L': opcode = Opcode.ALOAD; nextLVIndex += 1; curStack += 1; break; case 'J': opcode = Opcode.LLOAD; nextLVIndex += 2; curStack += 2; break; case 'D': opcode = Opcode.DLOAD; nextLVIndex += 2; curStack += 2; break; default: throw new ThreadCheckException("Parameter type no. " + paramIndex + ", " + t + ", is unknown in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } AInstruction load = Opcode.getShortestLoadStoreInstruction(opcode, (short) lvIndex); il.insertInstr(load, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; ++paramIndex; lvIndex = nextLVIndex; } if (curStack > maxStack) { maxStack = curStack; } ReferenceInstruction predicateCallInstr = new ReferenceInstruction(Opcode.INVOKESTATIC, (short) 0); int predicateCallIndex = predicateCF.addMethodToConstantPool(memberPAR.predicateClass.replace('.', '/'), memberPAR.predicateMI.getName().toString(), memberPAR.predicateMI.getDescriptor().toString()); predicateCallInstr.setReference(predicateCallIndex); il.insertInstr(predicateCallInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if ((par.combineMode == Combine.Mode.NOT) || ((par.combineMode == Combine.Mode.IMPLIES) && (memberCount == 1))) { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.SWAP), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ISUB), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if (par.combineMode == Combine.Mode.OR) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else if ((par.combineMode == Combine.Mode.AND) || (par.combineMode == Combine.Mode.NOT)) { il.insertInstr(new GenericInstruction(Opcode.IAND), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(new GenericInstruction(Opcode.IADD), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.IMPLIES) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else { assert false; } res = il.advanceIndex(); assert res == true; il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; WideBranchInstruction br2 = new WideBranchInstruction(Opcode.GOTO_W, il.getIndex() + 1); il.insertInstr(br2, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int jumpIndex = il.getIndex(); il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; res = il.rewindIndex(3); assert res == true; BranchInstruction br1 = new BranchInstruction(Opcode.IF_ICMPEQ, jumpIndex); il.insertInstr(br1, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(4); assert res == true; } else { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.deleteInstr(predicateMI.getCodeAttributeInfo()); predicateMI.getCodeAttributeInfo().setCode(il.getCode()); props.maxStack = Math.max(maxStack, 2); predicateMI.getCodeAttributeInfo().setProperties(props.maxStack, props.maxLocals); try { FileOutputStream fos = new FileOutputStream(clonedFile); predicateCF.write(fos); fos.close(); } catch (IOException e) { throw new ThreadCheckException("Could not write cloned predicate class file, target=" + clonedFile); } } gr = new PredicateAnnotationRecord(par.annotation, predicateClass, predicateMI, paramNames, paramTypes, new ArrayList<AAnnotationsAttributeInfo.Annotation.AMemberValue>(), par.passArguments, null, new HashMap<String, ArrayList<PredicateAnnotationRecord>>()); _generatedPredicateRecords.put(hashKey, gr); return gr; } Code Sample 2: public void run() { m_stats.setRunning(); URL url = m_stats.url; if (url != null) { try { URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; handleHTTPConnection(httpConnection, m_stats); } else { System.out.println("Unknown URL Connection Type " + url); } } catch (java.io.IOException ioe) { m_stats.setStatus(m_stats.IOError); m_stats.setErrorString("Error making or reading from connection" + ioe.toString()); } } m_stats.setDone(); m_manager.threadFinished(this); }
11
Code Sample 1: public static String encryptSHA(String pwd) throws NoSuchAlgorithmException { MessageDigest d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(pwd.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(d.digest()); } Code Sample 2: public byte[] authClient(String host, String user, String passwd, String realm, String serverChallenge) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream b64os = new BASE64EncoderStream(bos, Integer.MAX_VALUE); SecureRandom random; try { random = new SecureRandom(); md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { if (debugout != null) debugout.println("DEBUG DIGEST-MD5: " + ex); throw new IOException(ex.toString()); } StringBuffer result = new StringBuffer(); uri = "smtp/" + host; String nc = "00000001"; String qop = "auth"; byte[] bytes = new byte[32]; int resp; if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Begin authentication ..."); Hashtable map = tokenize(serverChallenge); if (realm == null) { String text = (String) map.get("realm"); realm = text != null ? new StringTokenizer(text, ",").nextToken() : host; } String nonce = (String) map.get("nonce"); random.nextBytes(bytes); b64os.write(bytes); b64os.flush(); String cnonce = bos.toString(); bos.reset(); md5.update(md5.digest(ASCIIUtility.getBytes(user + ":" + realm + ":" + passwd))); md5.update(ASCIIUtility.getBytes(":" + nonce + ":" + cnonce)); clientResponse = toHex(md5.digest()) + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":"; md5.update(ASCIIUtility.getBytes("AUTHENTICATE:" + uri)); md5.update(ASCIIUtility.getBytes(clientResponse + toHex(md5.digest()))); result.append("username=\"" + user + "\""); result.append(",realm=\"" + realm + "\""); result.append(",qop=" + qop); result.append(",nc=" + nc); result.append(",nonce=\"" + nonce + "\""); result.append(",cnonce=\"" + cnonce + "\""); result.append(",digest-uri=\"" + uri + "\""); result.append(",response=" + toHex(md5.digest())); if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Response => " + result.toString()); b64os.write(ASCIIUtility.getBytes(result.toString())); b64os.flush(); return bos.toByteArray(); }
00
Code Sample 1: public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); } Code Sample 2: public void login() { if (email.isEmpty() || pass.isEmpty()) { NotifyUtil.warn("Acount Data", "You need to specify and account e-mail and password.", false); return; } final ProgressHandle handle = ProgressHandleFactory.createHandle("Connecting to Facebook ..."); final Runnable task = new Runnable() { @Override public void run() { handle.start(); handle.switchToIndeterminate(); FacebookJsonRestClient client = new FacebookJsonRestClient(API_KEY, SECRET); client.setIsDesktop(true); HttpURLConnection connection; List<String> cookies; try { String token = client.auth_createToken(); String post_url = "http://www.facebook.com/login.php"; String get_url = "http://www.facebook.com/login.php" + "?api_key=" + API_KEY + "&v=1.0" + "&auth_token=" + token; HttpURLConnection.setFollowRedirects(true); connection = (HttpURLConnection) new URL(get_url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); connection.connect(); cookies = connection.getHeaderFields().get("Set-Cookie"); connection = (HttpURLConnection) new URL(post_url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } String params = "api_key=" + API_KEY + "&auth_token=" + token + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pass=" + URLEncoder.encode(pass, "UTF-8") + "&v=1.0"; connection.setRequestProperty("Content-Length", Integer.toString(params.length())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(params.toString().getBytes("UTF-8")); connection.getOutputStream().close(); cookies = connection.getHeaderFields().get("Set-Cookie"); if (cookies == null) { ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String url = "http://www.chartsy.org/facebook/"; DesktopUtil.browseAndWarn(url, null); } }; NotifyUtil.show("Application Permission", "You need to grant permission first.", MessageType.WARNING, listener, false); connection.disconnect(); loggedIn = false; } else { sessionKey = client.auth_getSession(token); sessionSecret = client.getSessionSecret(); loggedIn = true; } connection.disconnect(); handle.finish(); } catch (FacebookException fex) { handle.finish(); NotifyUtil.error("Login Error", fex.getMessage(), fex, false); } catch (IOException ioex) { handle.finish(); NotifyUtil.error("Login Error", ioex.getMessage(), ioex, false); } } }; WindowManager.getDefault().invokeWhenUIReady(task); }
00
Code Sample 1: byte[] calculateDigest(String value) { try { MessageDigest mg = MessageDigest.getInstance("SHA1"); mg.update(value.getBytes()); return mg.digest(); } catch (Exception e) { throw Bark.unchecker(e); } } Code Sample 2: public static void compress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(srcFile)); output = new GZIPOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
11
Code Sample 1: private static void addFile(File file, TarArchiveOutputStream taos) throws IOException { String filename = null; filename = file.getName(); TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } Code Sample 2: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
11
Code Sample 1: public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } } Code Sample 2: public static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException { GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile)); File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); FileOutputStream fos = new FileOutputStream(outFile); byte[] buf = new byte[100000]; int len; while ((len = gin.read(buf)) > 0) fos.write(buf, 0, len); gin.close(); fos.close(); if (deleteGzipfileOnSuccess) infile.delete(); return outFile; }
11
Code Sample 1: public ServiceAdapterIfc deploy(String session, String name, byte jarBytes[], String jarName, String serviceClass, String serviceInterface) throws RemoteException, MalformedURLException, StartServiceException, SessionException { try { File jarFile = new File(jarName); jarName = jarFile.getName(); String jarName2 = jarName; jarFile = new File(jarName2); int n = 0; while (jarFile.exists()) { jarName2 = jarName + n++; jarFile = new File(jarName2); } FileOutputStream fos = new FileOutputStream(jarName2); IOUtils.copy(new ByteArrayInputStream(jarBytes), fos); SCClassLoader cl = new SCClassLoader(new URL[] { new URL("file://" + jarFile.getAbsolutePath()) }, getMasterNode().getSCClassLoaderCounter()); return startService(session, name, serviceClass, serviceInterface, cl); } catch (SessionException e) { throw e; } catch (Exception e) { throw new StartServiceException("Could not deploy service: " + e.getMessage(), e); } } Code Sample 2: public static void main(String args[]) throws IOException, TrimmerException, DataStoreException { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("ace", "path to ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("phd", "path to phd file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("out", "path to new ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("min_sanger", "min sanger end coveage default =" + DEFAULT_MIN_SANGER_END_CLONE_CVG).build()); options.addOption(new CommandLineOptionBuilder("min_biDriection", "min bi directional end coveage default =" + DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE).build()); options.addOption(new CommandLineOptionBuilder("ignore_threshold", "min end coveage threshold to stop trying to trim default =" + DEFAULT_IGNORE_END_CVG_THRESHOLD).build()); CommandLine commandLine; PhdDataStore phdDataStore = null; AceContigDataStore datastore = null; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int minSangerEndCloneCoverage = commandLine.hasOption("min_sanger") ? Integer.parseInt(commandLine.getOptionValue("min_sanger")) : DEFAULT_MIN_SANGER_END_CLONE_CVG; int minBiDirectionalEndCoverage = commandLine.hasOption("min_biDriection") ? Integer.parseInt(commandLine.getOptionValue("min_biDriection")) : DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE; int ignoreThresholdEndCoverage = commandLine.hasOption("ignore_threshold") ? Integer.parseInt(commandLine.getOptionValue("ignore_threshold")) : DEFAULT_IGNORE_END_CVG_THRESHOLD; AceContigTrimmer trimmer = new NextGenClosureAceContigTrimmer(minSangerEndCloneCoverage, minBiDirectionalEndCoverage, ignoreThresholdEndCoverage); File aceFile = new File(commandLine.getOptionValue("ace")); File phdFile = new File(commandLine.getOptionValue("phd")); phdDataStore = new DefaultPhdFileDataStore(phdFile); datastore = new IndexedAceFileDataStore(aceFile); File tempFile = File.createTempFile("nextGenClosureAceTrimmer", ".ace"); tempFile.deleteOnExit(); OutputStream tempOut = new FileOutputStream(tempFile); int numberOfContigs = 0; int numberOfTotalReads = 0; for (AceContig contig : datastore) { AceContig trimmedAceContig = trimmer.trimContig(contig); if (trimmedAceContig != null) { numberOfContigs++; numberOfTotalReads += trimmedAceContig.getNumberOfReads(); AceFileWriter.writeAceFile(trimmedAceContig, phdDataStore, tempOut); } } IOUtil.closeAndIgnoreErrors(tempOut); OutputStream masterAceOut = new FileOutputStream(new File(commandLine.getOptionValue("out"))); masterAceOut.write(String.format("AS %d %d%n", numberOfContigs, numberOfTotalReads).getBytes()); InputStream tempInput = new FileInputStream(tempFile); IOUtils.copy(tempInput, masterAceOut); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); } finally { IOUtil.closeAndIgnoreErrors(phdDataStore, datastore); } }
00
Code Sample 1: private boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) { try { String ret; String xml; String moviehash = getHash(movieFile); String moviebytesize = String.valueOf(movieFile.length()); xml = generateXMLRPCSS(moviehash, moviebytesize); ret = sendRPC(xml); String subDownloadLink = getValue("SubDownloadLink", ret); if (subDownloadLink.equals("")) { String moviefilename = movieFile.getName(); if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) { String subfilename = subtitleFile.getName(); int index = subfilename.lastIndexOf("."); String query = subfilename.substring(0, index); xml = generateXMLRPCSS(query); ret = sendRPC(xml); subDownloadLink = getValue("SubDownloadLink", ret); } } if (subDownloadLink.equals("")) { logger.finer("OpenSubtitles Plugin: Subtitle not found for " + movie.getBaseName()); return false; } logger.finer("OpenSubtitles Plugin: Download subtitle for " + movie.getBaseName()); URL url = new URL(subDownloadLink); HttpURLConnection connection = (HttpURLConnection) (url.openConnection()); connection.setRequestProperty("Connection", "Close"); InputStream inputStream = connection.getInputStream(); int code = connection.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { logger.severe("OpenSubtitles Plugin: Download Failed"); return false; } GZIPInputStream a = new GZIPInputStream(inputStream); OutputStream out = new FileOutputStream(subtitleFile); byte buf[] = new byte[1024]; int len; while ((len = a.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); movie.setSubtitles(true); return true; } catch (Exception e) { logger.severe("OpenSubtitles Plugin: Download Exception (Movie Not Found)"); return false; } } Code Sample 2: public Dbf(URL url) throws java.io.IOException, DbfFileException { if (DEBUG) System.out.println("---->uk.ac.leeds.ccg.dbffile.Dbf constructed. Will identify itself as " + DBC); URLConnection uc = url.openConnection(); InputStream in = uc.getInputStream(); EndianDataInputStream sfile = new EndianDataInputStream(in); init(sfile); }
00
Code Sample 1: public List<String[]> getCSV(String name) { return new ResourceLoader<List<String[]>>(name) { @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } } }.get(); } Code Sample 2: private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:\\Rock Lee.jpg"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("file", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into bayfiles.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("Upload response : " + uploadresponse); downloadlink = parseResponse(uploadresponse, "\"downloadUrl\":\"", "\""); downloadlink = downloadlink.replaceAll("\\\\", ""); deletelink = parseResponse(uploadresponse, "\"deleteUrl\":\"", "\""); deletelink = deletelink.replaceAll("\\\\", ""); System.out.println("Download link : " + downloadlink); System.out.println("Delete link : " + deletelink); }
00
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); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + 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(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); 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 boolean BMPfromURL(URL url, MainClass mc) { TextField TF = mc.TF; PixCanvas canvas = mc.canvas; Image image = null; try { image = Toolkit.getDefaultToolkit().createImage(BMPReader.getBMPImage(url.openStream())); } catch (IOException e) { return false; } if (image == null) { TF.setText("Error not a typical image BMP format"); return false; } MediaTracker tr = new MediaTracker(canvas); tr.addImage(image, 0); try { tr.waitForID(0); } catch (InterruptedException e) { } ; if (tr.isErrorID(0)) { Tools.debug(OpenOther.class, "Tracker error " + tr.getErrorsAny().toString()); return false; } PixObject po = new PixObject(url, image, canvas, false, null); mc.vimages.addElement(po); TF.setText(url.toString()); canvas.repaint(); return true; }
11
Code Sample 1: public static String encodeMD5(String value) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); BASE64Encoder encoder = new BASE64Encoder(); md.update(value.getBytes()); byte[] raw = md.digest(); result = encoder.encode(raw); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } Code Sample 2: private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
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: private static void zipFolder(File folder, ZipOutputStream zipOutputStream, String relativePath) throws IOException { File[] children = folder.listFiles(); for (int i = 0; i < children.length; i++) { File child = children[i]; if (child.isFile()) { String zipEntryName = children[i].getCanonicalPath().replace(relativePath + File.separator, ""); ZipEntry entry = new ZipEntry(zipEntryName); zipOutputStream.putNextEntry(entry); InputStream inputStream = new FileInputStream(child); IOUtils.copy(inputStream, zipOutputStream); inputStream.close(); } else { ZipUtil.zipFolder(child, zipOutputStream, relativePath); } } }
00
Code Sample 1: public boolean check(int timeout) { StringBuilder result = null; java.net.URL url; java.io.InputStream in = null; try { url = new java.net.URL(location + "/prisms?method=test"); java.net.URLConnection conn = url.openConnection(); conn.setConnectTimeout(timeout); in = conn.getInputStream(); java.io.Reader reader = new java.io.InputStreamReader(in); result = new StringBuilder(); int read = reader.read(); while (read >= 0) { result.append((char) read); read = reader.read(); } } catch (java.io.IOException e) { log.error("Instance check failed", e); if (in != null) try { in.close(); } catch (java.io.IOException e2) { } } return result != null && result.toString().startsWith("success"); } Code Sample 2: protected void xInitGUI() { this.jlHead.setText(formater.getText("select_marc21_title")); this.jlResId.setText(formater.getText("select_marc21_label_text")); this.jlResId.setToolTipText(formater.getText("select_marc21_label_description")); ElvisListModel model = new ElvisListModel(); this.jlResourceList.setModel(model); try { URL urlListResources = new URL(ElvisRegistry.getInstance().getProperty("elvis.server") + "/servlet/listResources?xpath=document()//Book"); InputStream streamResources = urlListResources.openStream(); XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser(); xpp.setInput(new InputStreamReader(streamResources)); int type = xpp.getEventType(); while (type != XmlPullParser.END_DOCUMENT) { if (type == XmlPullParser.START_TAG && "Resource".equals(xpp.getName())) { model.add(xpp.getAttributeValue("", "resId"), xpp.getAttributeValue("", "author"), xpp.getAttributeValue("", "title")); } type = xpp.next(); } streamResources.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (XmlPullParserException xppe) { xppe.printStackTrace(); } ListSelectionModel selectionModel = this.jlResourceList.getSelectionModel(); selectionModel.addListSelectionListener(new ListSelectionListener() { /** * @param e Description of the Parameter * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent) */ public void valueChanged(ListSelectionEvent e) { int index = e.getFirstIndex(); boolean isAdjusting = e.getValueIsAdjusting(); if (!isAdjusting) { ElvisListModel _model = (ElvisListModel) jlResourceList.getModel(); jtfResId.setText(_model.get(index).getId()); } } }); }
11
Code Sample 1: public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; 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(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); } Code Sample 2: private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
11
Code Sample 1: private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); } Code Sample 2: public static boolean copyFile(String fromfile, String tofile) { File from = new File(fromfile); File to = new File(tofile); if (!from.exists()) return false; if (to.exists()) { log.error(tofile + "exists already"); return false; } BufferedInputStream in = null; BufferedOutputStream out = null; FileInputStream fis = null; FileOutputStream ois = null; boolean flag = true; try { to.createNewFile(); fis = new FileInputStream(from); ois = new FileOutputStream(to); in = new BufferedInputStream(fis); out = new BufferedOutputStream(ois); byte[] buf = new byte[2048]; int readBytes = 0; while ((readBytes = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, readBytes); } } catch (IOException e) { log.error(e); flag = false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log.error(e); flag = false; } } return flag; }
00
Code Sample 1: private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); } Code Sample 2: public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
00
Code Sample 1: public static String getHashedPasswordTc(String password) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(password.getBytes()); byte[] buf = d.digest(); char[] cbf = new char[buf.length * 2]; for (int jj = 0, kk = 0; jj < buf.length; jj++) { cbf[kk++] = "0123456789abcdef".charAt((buf[jj] >> 4) & 0x0F); cbf[kk++] = "0123456789abcdef".charAt(buf[jj] & 0x0F); } return new String(cbf); } Code Sample 2: String[] openUrlAsList(String address) { IJ.showStatus("Connecting to " + IJ.URL); Vector v = new Vector(); try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while (true) { line = br.readLine(); if (line == null) break; if (!line.equals("")) v.addElement(line); } br.close(); } catch (Exception e) { } String[] lines = new String[v.size()]; v.copyInto((String[]) lines); IJ.showStatus(""); return lines; }
00
Code Sample 1: public String contactService(String service, StringBuffer xmlRequest) throws Exception { Logger.debug(UPSConnections.class, "UPS CONNECTIONS ***** Started " + service + " " + new Date().toString() + " *****"); HttpURLConnection connection; URL url; String response = ""; try { Logger.debug(UPSConnections.class, "connect to " + protocol + "://" + hostname + "/" + URLPrefix + "/" + service); if (protocol.equalsIgnoreCase("https")) { java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.getProperties().put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); url = new URL(protocol + "://" + hostname + "/" + URLPrefix + "/" + service); connection = (HttpsURLConnection) url.openConnection(); } else { url = new URL(protocol + "://" + hostname + "/" + URLPrefix + "/" + service); connection = (HttpURLConnection) url.openConnection(); } Logger.debug(UPSConnections.class, "Establishing connection with " + url.toString()); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); OutputStream out = connection.getOutputStream(); StringBuffer request = new StringBuffer(); request.append(accessXMLRequest()); request.append(xmlRequest); out.write((request.toString()).getBytes()); Logger.debug(UPSConnections.class, "Transmission sent to " + url.toString() + ":\n" + xmlRequest); out.close(); try { response = readURLConnection(connection); } catch (Exception e) { Logger.debug(UPSConnections.class, "Error in reading URL Connection" + e.getMessage()); throw e; } Logger.debug(UPSConnections.class, "Response = " + response); } catch (Exception e1) { Logger.info(UPSConnections.class, "Error sending data to server" + e1.toString()); Logger.debug(UPSConnections.class, "Error sending data to server" + e1.toString()); } finally { Logger.info(UPSConnections.class, "****** Transmission Finished " + service + " " + new Date().toString() + " *********"); Logger.debug(UPSConnections.class, "****** Transmission Finished " + service + " " + new Date().toString() + " *********"); } return response; } Code Sample 2: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/jar"); byte[] bufor = new byte[BUF_LEN]; ServletContext context = getServletContext(); URL url = context.getResource(FILE_NAME); InputStream in = url.openStream(); OutputStream out = response.getOutputStream(); while (in.read(bufor) != -1) out.write(bufor); in.close(); out.close(); }
00
Code Sample 1: public static boolean start(RootDoc root) { Logger log = Logger.getLogger("DocletGenerator"); if (destination == null) { try { ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8"); String fn = System.getenv("annocultor.xconverter.destination.file.name"); fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn; destination = new File(fn); if (destination.exists()) { destination.delete(); } FileOutputStream os; os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd")); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterTemplate.xsd")), os); os.close(); os = new FileOutputStream(destination); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterInclude.xsd")), os); os.close(); } catch (Exception e) { try { throw new RuntimeException("On destination " + destination.getCanonicalPath(), e); } catch (IOException e1) { throw new RuntimeException(e1); } } } try { String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n"); int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); if (breakPoint < 0) { throw new Exception("Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); } String preambula = s.substring(0, breakPoint); String appendix = s.substring(breakPoint); destination.delete(); PrintWriter schemaWriter = new PrintWriter(destination); schemaWriter.print(preambula); ClassDoc[] classes = root.classes(); for (int i = 0; i < classes.length; ++i) { ClassDoc cd = classes[i]; PrintWriter documentationWriter = null; if (getSuperClasses(cd).contains(Rule.class.getName())) { for (ConstructorDoc constructorDoc : cd.constructors()) { if (constructorDoc.isPublic()) { if (isMeantForXMLAccess(constructorDoc)) { if (documentationWriter == null) { File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml"); documentationWriter = new PrintWriter(file); log.info("Generating doc for rule " + file.getCanonicalPath()); printRuleDocStart(cd, documentationWriter); } boolean initFound = false; for (MethodDoc methodDoc : cd.methods()) { if ("init".equals(methodDoc.name())) { if (methodDoc.parameters().length == 0) { initFound = true; break; } } } if (!initFound) { } printConstructorSchema(constructorDoc, schemaWriter); if (documentationWriter != null) { printConstructorDoc(constructorDoc, documentationWriter); } } } } } if (documentationWriter != null) { printRuleDocEnd(documentationWriter); } } schemaWriter.print(appendix); schemaWriter.close(); log.info("Saved to " + destination.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } return true; } Code Sample 2: private static String hashPassword(String password, String customsalt) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT1 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT2 + customsalt; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash) + "|" + customsalt; }
00
Code Sample 1: public void myCheckCredHandler(View v) { Log.d("login_section", "entered handler"); EditText Username = (EditText) findViewById(R.id.Username); EditText Password = (EditText) findViewById(R.id.user_pass); String username_S = Username.getText().toString(); String pass_S = Password.getText().toString(); TextView ltv = (TextView) findViewById(R.id.LoginPagetv); HttpClient httpclient = createHttpClient(); HttpPost httppost = new HttpPost(authenticationURL); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("login", username_S)); nameValuePairs.add(new BasicNameValuePair("password", pass_S)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); Log.d("login_section", responseBody); JSONObject jsonObject = new JSONObject(responseBody); if (status == this.statusOK && jsonObject.getBoolean("logged_in")) { ltv.setText("You have been logged in. :D"); etracks.setLogged(true); etracks.setUserToken(jsonObject.getString("user_token")); Intent it = new Intent(Intent.ACTION_VIEW); it.setClassName(this, etracks.class.getName()); this.finish(); startActivity(it); } else if (status == this.statusUnprocessable && !jsonObject.getBoolean("logged_in")) { if (!jsonObject.isNull("errors")) ltv.setText(jsonObject.getString("errors")); else ltv.setText("login unsuccessful"); } else Log.d("login_section", "what just happened?"); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (JSONException e) { e.printStackTrace(); } } Code Sample 2: public void genCreateSchema(DiagramModel diagramModel, String source) { try { con.setAutoCommit(false); stmt = con.createStatement(); Collection boxes = diagramModel.getBoxes(); BoxModel box; ItemModel item; String sqlQuery; int counter = 0; for (Iterator x = boxes.iterator(); x.hasNext(); ) { box = (BoxModel) x.next(); if (!box.isAbstractDef()) { sqlQuery = sqlCreateTableBegin(box); Collection items = box.getItems(); for (Iterator y = items.iterator(); y.hasNext(); ) { item = (ItemModel) y.next(); sqlQuery = sqlQuery + sqlColumn(item); } sqlQuery = sqlQuery + sqlForeignKeyColumns(box); sqlQuery = sqlQuery + sqlPrimaryKey(box); sqlQuery = sqlQuery + sqlUniqueKey(box); sqlQuery = sqlQuery + sqlCreateTableEnd(box, source); System.out.println(sqlQuery); try { stmt.executeUpdate(sqlQuery); counter++; } catch (SQLException e) { String tableName = box.getName(); System.out.println("// Problem while creating table " + tableName + " : " + e.getMessage()); String msg = Para.getPara().getText("tableNotCreated") + " -- " + tableName; this.informUser(msg); } } } this.genCreateForeignKeys(diagramModel); con.commit(); if (counter > 0) { String msg = Para.getPara().getText("schemaCreated") + " -- " + counter + " " + Para.getPara().getText("tables"); this.informUser(msg); } else { this.informUser(Para.getPara().getText("schemaNotCreated")); } } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the JDBC schema generation! "); try { con.rollback(); this.informUser(Para.getPara().getText("schemaNotCreated")); } catch (SQLException e1) { System.out.println(e1.getMessage() + " // Problem with the connection rollback! "); } } finally { try { con.setAutoCommit(true); stmt.close(); } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the statement closing! "); } } }
11
Code Sample 1: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
11
Code Sample 1: public String setEncryptedPassword(String rawPassword) { String out = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(rawPassword.getBytes()); byte raw[] = md.digest(); out = new String(); for (int x = 0; x < raw.length; x++) { String hex2 = Integer.toHexString((int) raw[x] & 0xFF); if (1 == hex2.length()) { hex2 = "0" + hex2; } out += hex2; int a = 1; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return out; } Code Sample 2: public String MD5(String text) { try { 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); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: static boolean writeProperties(Map<String, String> customProps, File destination) throws IOException { synchronized (PropertiesIO.class) { L.info(Msg.msg("PropertiesIO.writeProperties.start")); File tempFile = null; BufferedInputStream existingCfgInStream = null; FileInputStream in = null; FileOutputStream out = null; PrintStream ps = null; FileChannel fromChannel = null, toChannel = null; String line = null; try { existingCfgInStream = new BufferedInputStream(destination.exists() ? new FileInputStream(destination) : defaultPropertiesStream()); tempFile = File.createTempFile("properties-", ".tmp", null); ps = new PrintStream(tempFile); while ((line = Utils.readLine(existingCfgInStream)) != null) { String lineReady2write = setupLine(line, customProps); ps.println(lineReady2write); } destination.getParentFile().mkdirs(); in = new FileInputStream(tempFile); out = new FileOutputStream(destination, false); fromChannel = in.getChannel(); toChannel = out.getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); L.info(Msg.msg("PropertiesIO.writeProperties.done").replace("#file#", destination.getAbsolutePath())); return true; } finally { if (existingCfgInStream != null) existingCfgInStream.close(); if (ps != null) ps.close(); if (fromChannel != null) fromChannel.close(); if (toChannel != null) toChannel.close(); if (out != null) out.close(); if (in != null) in.close(); if (tempFile != null && tempFile.exists()) tempFile.delete(); } } } Code Sample 2: public String output(final ComponentParameter compParameter) { InputStream inputStream; try { final URL url = new URL("http://xml.weather.yahoo.com/forecastrss?p=" + getPagelet().getOptionProperty("_weather_code") + "&u=c"); inputStream = url.openStream(); } catch (final IOException e) { return e.getMessage(); } final StringBuilder sb = new StringBuilder(); new AbstractXmlDocument(inputStream) { @Override protected void init() throws Exception { final Element root = getRoot(); final Namespace ns = root.getNamespaceForPrefix("yweather"); final Element channel = root.element("channel"); final String link = channel.elementText("link"); final Element item = channel.element("item"); Element ele = item.element(QName.get("condition", ns)); if (ele == null) { sb.append("ERROR"); return; } final String imgPath = getPagelet().getColumnBean().getPortalBean().getCssResourceHomePath(compParameter) + "/images/yahoo/"; String text, image; Date date = new SimpleDateFormat(YahooWeatherUtils.RFC822_MASKS[1], Locale.US).parse(ele.attributeValue("date")); final int temp = Integer.parseInt(ele.attributeValue("temp")); int code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append("<div style=\"line-height: normal;\"><a target=\"_blank\" href=\"").append(link).append("\"><img src=\""); sb.append(image).append("\" /></a>"); sb.append(YahooWeatherUtils.formatHour(date)).append(" - "); sb.append(text).append(" - ").append(temp).append("℃").append("<br>"); final Iterator<?> it = item.elementIterator(QName.get("forecast", ns)); while (it.hasNext()) { ele = (Element) it.next(); date = new SimpleDateFormat("dd MMM yyyy", Locale.US).parse(ele.attributeValue("date")); final int low = Integer.parseInt(ele.attributeValue("low")); final int high = Integer.parseInt(ele.attributeValue("high")); code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append(YahooWeatherUtils.formatWeek(date)).append(" ( "); sb.append(text).append(". "); sb.append(low).append("℃~").append(high).append("℃"); sb.append(" )<br>"); } sb.append("</div>"); } }; return sb.toString(); }
11
Code Sample 1: public static void loadConfig(DeviceEntry defaultDevice, EmulatorContext emulatorContext) { Config.defaultDevice = defaultDevice; Config.emulatorContext = emulatorContext; File configFile = new File(getConfigPath(), "config2.xml"); try { if (configFile.exists()) { loadConfigFile("config2.xml"); } else { configFile = new File(getConfigPath(), "config.xml"); if (configFile.exists()) { loadConfigFile("config.xml"); for (Enumeration e = getDeviceEntries().elements(); e.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) e.nextElement(); if (!entry.canRemove()) { continue; } removeDeviceEntry(entry); File src = new File(getConfigPath(), entry.getFileName()); File dst = File.createTempFile("dev", ".jar", getConfigPath()); IOUtils.copyFile(src, dst); entry.setFileName(dst.getName()); addDeviceEntry(entry); } } else { createDefaultConfigXml(); } saveConfig(); } } catch (IOException ex) { Logger.error(ex); createDefaultConfigXml(); } finally { if (configXml == null) { createDefaultConfigXml(); } } urlsMRU.read(configXml.getChildOrNew("files").getChildOrNew("recent")); initSystemProperties(); } Code Sample 2: private void post(String title, Document content, Set<String> tags) throws HttpException, IOException, TransformerException { PostMethod method = null; try { method = new PostMethod("http://www.blogger.com/feeds/" + this.blogId + "/posts/default"); method.addRequestHeader("GData-Version", String.valueOf(GDataVersion)); method.addRequestHeader("Authorization", "GoogleLogin auth=" + this.AuthToken); Document dom = this.domBuilder.newDocument(); Element entry = dom.createElementNS(Atom.NS, "entry"); dom.appendChild(entry); entry.setAttribute("xmlns", Atom.NS); Element titleNode = dom.createElementNS(Atom.NS, "title"); entry.appendChild(titleNode); titleNode.setAttribute("type", "text"); titleNode.appendChild(dom.createTextNode(title)); Element contentNode = dom.createElementNS(Atom.NS, "content"); entry.appendChild(contentNode); contentNode.setAttribute("type", "xhtml"); contentNode.appendChild(dom.importNode(content.getDocumentElement(), true)); for (String tag : tags) { Element category = dom.createElementNS(Atom.NS, "category"); category.setAttribute("scheme", "http://www.blogger.com/atom/ns#"); category.setAttribute("term", tag); entry.appendChild(category); } StringWriter out = new StringWriter(); this.xml2ascii.transform(new DOMSource(dom), new StreamResult(out)); method.setRequestEntity(new StringRequestEntity(out.toString(), "application/atom+xml", "UTF-8")); int status = getHttpClient().executeMethod(method); if (status == 201) { IOUtils.copyTo(method.getResponseBodyAsStream(), System.out); } else { throw new HttpException("post returned http-code=" + status + " expected 201 (CREATE)"); } } catch (TransformerException err) { throw err; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } }
11
Code Sample 1: private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(RuleParameter.MODIFICATION_EXCLUDES_DEFAULT.getValue()); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true, new AttackMailHandler()); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(RuleParameter.RESPONSE_MODIFICATIONS_DEFAULT.getValue()); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List<Pattern> tmpPatternsToExcludeCompleteTag = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeCompleteScript = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteTag = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteScript = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList<Integer[]>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList<Integer[]>(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); } Code Sample 2: private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } }
11
Code Sample 1: public void copy(String sourcePath, String targetPath) throws IOException { File sourceFile = new File(sourcePath); File targetFile = new File(targetPath); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(sourceFile); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) fileOutputStream.write(buffer, 0, bytesRead); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s265") + sourcePath, AcideLanguageManager.getInstance().getLabels().getString("s266"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s267") + targetPath, AcideLanguageManager.getInstance().getLabels().getString("268"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } } } Code Sample 2: private void copyThemeProviderClass() throws Exception { InputStream is = getClass().getResourceAsStream("/zkthemer/ThemeProvider.class"); if (is == null) throw new RuntimeException("Cannot find ThemeProvider.class"); File outFile = new File(theme.getJarRootFile(), "zkthemer/ThemeProvider.class"); outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); IOUtils.copy(is, out); out.close(); FileUtils.writeStringToFile(new File(theme.getJarRootFile(), "zkthemer.properties"), "theme=" + theme.getName() + "\r\nfileList=" + fileList.deleteCharAt(fileList.length() - 1).toString()); }
00
Code Sample 1: public void parseFile(String filespec, URL documentBase) { DataInputStream in = null; if (filespec == null || filespec.length() == 0) { in = new DataInputStream(System.in); } else { try { URL url = null; if (documentBase == null && _documentBase != null) { documentBase = _documentBase; } if (documentBase == null) { url = new URL(filespec); } else { try { url = new URL(documentBase, filespec); } catch (NullPointerException e) { url = new URL(filespec); } } in = new DataInputStream(url.openStream()); } catch (MalformedURLException e) { try { in = new DataInputStream(new FileInputStream(filespec)); } catch (FileNotFoundException me) { _errorMsg = new String[2]; _errorMsg[0] = "File not found: " + filespec; _errorMsg[1] = me.getMessage(); return; } catch (SecurityException me) { _errorMsg = new String[2]; _errorMsg[0] = "Security Exception: " + filespec; _errorMsg[1] = me.getMessage(); return; } } catch (IOException ioe) { _errorMsg = new String[3]; _errorMsg[0] = "Failure opening URL: "; _errorMsg[1] = " " + filespec; _errorMsg[2] = ioe.getMessage(); return; } } try { BufferedReader din = new BufferedReader(new InputStreamReader(in)); String line = din.readLine(); while (line != null) { _parseLine(line); line = din.readLine(); } } catch (MalformedURLException e) { _errorMsg = new String[2]; _errorMsg[0] = "Malformed URL: " + filespec; _errorMsg[1] = e.getMessage(); return; } catch (IOException e) { _errorMsg = new String[2]; _errorMsg[0] = "Failure reading data: " + filespec; _errorMsg[1] = e.getMessage(); _errorMsg[1] = e.getMessage(); } finally { try { in.close(); } catch (IOException me) { } } } Code Sample 2: private void _PostParser(Document document, AnnotationManager annoMan, Document htmldoc, String baseurl) { xformer = annoMan.getTransformer(); builder = annoMan.getBuilder(); String annohash = ""; if (document == null) return; NodeList ndlist = document.getElementsByTagNameNS(annoNS, "body"); if (ndlist.getLength() != 1) { System.out.println("Sorry Annotation Body was found " + ndlist.getLength() + " times"); return; } Element bodynode = (Element) ndlist.item(0); Node htmlNode = bodynode.getElementsByTagName("html").item(0); if (htmlNode == null) htmlNode = bodynode.getElementsByTagName("HTML").item(0); Document newdoc = builder.newDocument(); Element rootelem = newdoc.createElementNS(rdfNS, "r:RDF"); rootelem.setAttribute("xmlns:r", rdfNS); rootelem.setAttribute("xmlns:a", annoNS); rootelem.setAttribute("xmlns:d", dubNS); rootelem.setAttribute("xmlns:t", threadNS); newdoc.appendChild(rootelem); Element tmpelem; NodeList tmpndlist; Element annoElem = newdoc.createElementNS(annoNS, "a:Annotation"); rootelem.appendChild(annoElem); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "context").item(0); String context = tmpelem.getChildNodes().item(0).getNodeValue(); annoElem.setAttributeNS(annoNS, "a:context", context); NodeList elemcontl = tmpelem.getElementsByTagNameNS(alNS, "context-element"); Node ncontext_element = null; if (elemcontl.getLength() > 0) { Node old_context_element = elemcontl.item(0); ncontext_element = newdoc.importNode(old_context_element, true); } tmpndlist = document.getElementsByTagNameNS(dubNS, "title"); annoElem.setAttributeNS(dubNS, "d:title", tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "Default"); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "creator").item(0); annoElem.setAttributeNS(dubNS, "d:creator", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "created").item(0); annoElem.setAttributeNS(annoNS, "a:created", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "date").item(0); annoElem.setAttributeNS(dubNS, "d:date", tmpelem.getChildNodes().item(0).getNodeValue()); tmpndlist = document.getElementsByTagNameNS(dubNS, "language"); String language = (tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "en"); annoElem.setAttributeNS(dubNS, "d:language", language); Node typen = newdoc.importNode(document.getElementsByTagNameNS(rdfNS, "type").item(0), true); annoElem.appendChild(typen); Element contextn = newdoc.createElementNS(annoNS, "a:context"); contextn.setAttributeNS(rdfNS, "r:resource", context); annoElem.appendChild(contextn); Node annotatesn = newdoc.importNode(document.getElementsByTagNameNS(annoNS, "annotates").item(0), true); annoElem.appendChild(annotatesn); Element newbodynode = newdoc.createElementNS(annoNS, "a:body"); annoElem.appendChild(newbodynode); if (ncontext_element != null) { contextn.appendChild(ncontext_element); } else { System.out.println("No context element found, we create one..."); try { XPointer xptr = new XPointer(htmldoc); NodeRange xprange = xptr.getRange(context, htmldoc); Element context_elem = newdoc.createElementNS(alNS, "al:context-element"); context_elem.setAttributeNS(alNS, "al:text", xprange.getContentString()); context_elem.appendChild(newdoc.createTextNode(annoMan.generateContextString(xprange))); contextn.appendChild(context_elem); } catch (XPointerRangeException e2) { e2.printStackTrace(); } } WordFreq wf = new WordFreq(annoMan.extractTextFromNode(htmldoc)); Element docident = newdoc.createElementNS(alNS, "al:document-identifier"); annotatesn.appendChild(docident); docident.setAttributeNS(alNS, "al:orig-url", ((Element) annotatesn).getAttributeNS(rdfNS, "resource")); docident.setAttributeNS(alNS, "al:version", "1"); Iterator it = null; it = wf.getSortedWordlist(); Map.Entry ent; String word; int count; int i = 0; while (it.hasNext()) { ent = (Map.Entry) it.next(); word = ((String) ent.getKey()); count = ((Counter) ent.getValue()).count; if ((word.length() > 4) && (i < 10)) { Element wordelem = newdoc.createElementNS(alNS, "al:word"); wordelem.setAttributeNS(alNS, "al:freq", Integer.toString(count)); wordelem.appendChild(newdoc.createTextNode(word)); docident.appendChild(wordelem); i++; } } try { StringWriter strw = new StringWriter(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); xformer.transform(new DOMSource(newdoc), new StreamResult(strw)); messagedigest.update(strw.toString().getBytes()); byte[] md5bytes = messagedigest.digest(); annohash = ""; for (int b = 0; b < md5bytes.length; b++) { String s = Integer.toHexString(md5bytes[b] & 0xFF); annohash = annohash + ((s.length() == 1) ? "0" + s : s); } this.annohash = annohash; annoElem.setAttribute("xmlns:al", alNS); annoElem.setAttributeNS(alNS, "al:id", getAnnohash()); Location = (baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); newbodynode.setAttributeNS(rdfNS, "r:resource", baseurl + "/annotation/body/" + getAnnohash()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } annoMan.store(newdoc.getDocumentElement()); annoMan.createAnnoResource(newdoc.getDocumentElement(), getAnnohash()); if (htmlNode != null) annoMan.createAnnoBody(htmlNode, getAnnohash()); Location = (this.baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); this.responseDoc = newdoc; }
00
Code Sample 1: public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map templateContext, GenericDelegator delegator, Writer out, boolean cache) throws IOException, GeneralException { Map context = (Map) templateContext.get("context"); if (context == null) { context = FastMap.newInstance(); } String webSiteId = (String) templateContext.get("webSiteId"); if (UtilValidate.isEmpty(webSiteId)) { if (context != null) webSiteId = (String) context.get("webSiteId"); } String https = (String) templateContext.get("https"); if (UtilValidate.isEmpty(https)) { if (context != null) https = (String) context.get("https"); } String dataResourceId = dataResource.getString("dataResourceId"); String dataResourceTypeId = dataResource.getString("dataResourceTypeId"); if (UtilValidate.isEmpty(dataResourceTypeId)) { dataResourceTypeId = "SHORT_TEXT"; } if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) { String text = dataResource.getString("objectInfo"); writeText(dataResource, text, templateContext, mimeTypeId, locale, out); } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) { GenericValue electronicText; if (cache) { electronicText = delegator.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } else { electronicText = delegator.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } String text = electronicText.getString("textData"); writeText(dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_OBJECT")) { String text = (String) dataResource.get("dataResourceId"); writeText(dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.equals("URL_RESOURCE")) { String text = null; URL url = FlexibleLocation.resolveLocation(dataResource.getString("objectInfo")); if (url.getHost() != null) { InputStream in = url.openStream(); int c; StringWriter sw = new StringWriter(); while ((c = in.read()) != -1) { sw.write(c); } sw.close(); text = sw.toString(); } else { String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https); String sep = ""; if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { sep = "/"; } String fixedUrlStr = prefix + sep + url.toString(); URL fixedUrl = new URL(fixedUrlStr); text = (String) fixedUrl.getContent(); } out.write(text); } else if (dataResourceTypeId.endsWith("_FILE_BIN")) { writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_FILE")) { String dataResourceMimeTypeId = dataResource.getString("mimeTypeId"); String objectInfo = dataResource.getString("objectInfo"); String rootDir = (String) context.get("rootDir"); if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) { renderFile(dataResourceTypeId, objectInfo, rootDir, out); } else { writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } } else { throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText"); } } Code Sample 2: @Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
00
Code Sample 1: @Override public void runTask(HashMap pjobParameters) throws Exception { if (hasRequiredResources(isSubTask())) { String lstrSource = getSourceFilename(); String lstrTarget = getTargetFilename(); if (getSourceDirectory() != null) { lstrSource = getSourceDirectory() + File.separator + getSourceFilename(); } if (getTargetDirectory() != null) { lstrTarget = getTargetDirectory() + File.separator + getTargetFilename(); } GZIPInputStream lgzipInput = new GZIPInputStream(new FileInputStream(lstrSource)); OutputStream lfosGUnzip = new FileOutputStream(lstrTarget); byte[] buf = new byte[1024]; int len; while ((len = lgzipInput.read(buf)) > 0) lfosGUnzip.write(buf, 0, len); lgzipInput.close(); lfosGUnzip.close(); } } Code Sample 2: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
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: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); } Code Sample 2: public Object sendObjectRequestToSpecifiedServer(java.lang.String serverName, java.lang.String servletName, java.lang.Object request) { Object reqxml = null; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { java.net.URL url = new java.net.URL("http://" + serverName + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream os = urlconn.getOutputStream(); java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.ObjectOutputStream dos = new java.io.ObjectOutputStream(gop); dos.writeObject(request); dos.flush(); dos.close(); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.ObjectInputStream br = new java.io.ObjectInputStream(gip); reqxml = br.readObject(); } catch (Exception exp) { exp.printStackTrace(System.out); System.out.println("Exception in Servlet Connector: " + exp); } return reqxml; }
11
Code Sample 1: public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); } Code Sample 2: 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(); }
11
Code Sample 1: public void _saveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String subcmd) throws WebAssetException, Exception { long maxsize = 50; long maxwidth = 3000; long maxheight = 3000; long minheight = 10; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); try { UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req); String parent = ParamUtil.getString(req, "parent"); int countFiles = ParamUtil.getInteger(req, "countFiles"); int fileCounter = 0; Folder folder = (Folder) InodeFactory.getInode(parent, Folder.class); _checkUserPermissions(folder, user, PERMISSION_WRITE); String userId = user.getUserId(); String customMessage = "Some file does not match the filters specified by the folder: "; boolean filterError = false; for (int k = 0; k < countFiles; k++) { File file = new File(); String title = ParamUtil.getString(req, "title" + k); String friendlyName = ParamUtil.getString(req, "friendlyName" + k); Date publishDate = new Date(); String fileName = ParamUtil.getString(req, "fileName" + k); fileName = checkMACFileName(fileName); if (!FolderFactory.matchFilter(folder, fileName)) { customMessage += fileName + ", "; filterError = true; continue; } if (fileName.length() > 0) { String mimeType = FileFactory.getMimeType(fileName); String URI = folder.getPath() + fileName; String suffix = UtilMethods.getFileExtension(fileName); file.setTitle(title); file.setFileName(fileName); file.setFriendlyName(friendlyName); file.setPublishDate(publishDate); file.setModUser(userId); InodeFactory.saveInode(file); String filePath = FileFactory.getRealAssetsRootPath(); new java.io.File(filePath).mkdir(); java.io.File uploadedFile = uploadReq.getFile("uploadedFile" + k); Logger.debug(this, "bytes" + uploadedFile.length()); file.setSize((int) uploadedFile.length() - 2); file.setMimeType(mimeType); Host host = HostFactory.getCurrentHost(httpReq); Identifier ident = IdentifierFactory.getIdentifierByURI(URI, host); String message = ""; if ((FileFactory.existsFileName(folder, fileName))) { InodeFactory.deleteInode(file); message = "The uploaded file " + fileName + " already exists in this folder"; SessionMessages.add(req, "custommessage", message); } else { String fileInodePath = String.valueOf(file.getInode()); if (fileInodePath.length() == 1) { fileInodePath = fileInodePath + "0"; } fileInodePath = fileInodePath.substring(0, 1) + java.io.File.separator + fileInodePath.substring(1, 2); new java.io.File(filePath + java.io.File.separator + fileInodePath.substring(0, 1)).mkdir(); new java.io.File(filePath + java.io.File.separator + fileInodePath).mkdir(); java.io.File f = new java.io.File(filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); java.io.FileOutputStream fout = new java.io.FileOutputStream(f); FileChannel outputChannel = fout.getChannel(); FileChannel inputChannel = new java.io.FileInputStream(uploadedFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); outputChannel.force(false); outputChannel.close(); inputChannel.close(); Logger.debug(this, "SaveFileAction New File in =" + filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); if (suffix.equals("jpg") || suffix.equals("gif")) { com.dotmarketing.util.Thumbnail.resizeImage(filePath + java.io.File.separator + fileInodePath + java.io.File.separator, String.valueOf(file.getInode()), suffix); int height = javax.imageio.ImageIO.read(f).getHeight(); file.setHeight(height); Logger.debug(this, "File height=" + height); int width = javax.imageio.ImageIO.read(f).getWidth(); file.setWidth(width); Logger.debug(this, "File width=" + width); long size = (f.length() / 1024); WebAssetFactory.createAsset(file, userId, folder); } else { WebAssetFactory.createAsset(file, userId, folder); } WorkingCache.addToWorkingAssetToCache(file); _setFilePermissions(folder, file, user); fileCounter += 1; if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH)) { try { PublishFactory.publishAsset(file, httpReq); if (fileCounter > 1) { SessionMessages.add(req, "message", "message.file_asset.save"); } else { SessionMessages.add(req, "message", "message.fileupload.save"); } } catch (WebAssetException wax) { Logger.error(this, wax.getMessage(), wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } } } } } if (filterError) { customMessage = customMessage.substring(0, customMessage.lastIndexOf(",")); SessionMessages.add(req, "custommessage", customMessage); } } catch (IOException e) { Logger.error(this, "Exception saving file: " + e.getMessage()); throw new ActionException(e.getMessage()); } } Code Sample 2: public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
00
Code Sample 1: public boolean chequearMarca(int a, int m, int d) { boolean existe = false; try { cantidadArchivos = obtenerCantidad() + 1; String filenametxt = ""; String filenamezip = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (ano == a && mes == m && dia == d) existe = true; input.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } return (existe); } Code Sample 2: public static void loadPages() throws IOException { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Collection<Class<? extends BasePage>> pages = new ArrayList<Class<? extends BasePage>>(); Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName()); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int comment = line.indexOf('#'); if (comment >= 0) line = line.substring(0, comment); String name = line.trim(); if (name.length() == 0) continue; Class<?> clz = Class.forName(name, true, ldr); if (BasePage.class.isAssignableFrom(clz)) { pages.add(clz.asSubclass(BasePage.class)); } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { is.close(); } catch (Exception ex) { } } } pageTypes = pages; }
00
Code Sample 1: public boolean Load_Clickable_Peaks_Source_File(String tam) { if (tam == null) return false; try { URL url = new URL(getDocumentBase(), tam); InputStream stream = url.openStream(); DataInputStream fichier = new DataInputStream(stream); texte = new Vector(); String s; while ((s = fichier.readLine()) != null) { texte.addElement(s); } My_ZoneVisu.Nb_Clickable_Peaks = texte.size(); } catch (Exception e) { return false; } My_ZoneVisu.Peak_Start = new double[My_ZoneVisu.Nb_Clickable_Peaks]; My_ZoneVisu.Peak_Stop = new double[My_ZoneVisu.Nb_Clickable_Peaks]; My_ZoneVisu.Peak_Html = new String[My_ZoneVisu.Nb_Clickable_Peaks]; int cpt_tokens = 0; int i = 0; StringTokenizer mon_token; while (cpt_tokens < My_ZoneVisu.Nb_Clickable_Peaks) { do { String mysub = (String) texte.elementAt(cpt_tokens); mon_token = new StringTokenizer(mysub, " "); cpt_tokens++; } while (cpt_tokens < My_ZoneVisu.Nb_Clickable_Peaks && mon_token.hasMoreTokens() == false); if (mon_token.hasMoreTokens() == true) { My_ZoneVisu.Peak_Start[i] = Double.valueOf(mon_token.nextToken()).doubleValue(); My_ZoneVisu.Peak_Stop[i] = Double.valueOf(mon_token.nextToken()).doubleValue(); if (My_ZoneVisu.Peak_Start[i] > My_ZoneVisu.Peak_Stop[i]) { double temp = My_ZoneVisu.Peak_Start[i]; My_ZoneVisu.Peak_Start[i] = My_ZoneVisu.Peak_Stop[i]; My_ZoneVisu.Peak_Stop[i] = temp; } My_ZoneVisu.Peak_Html[i] = (String) mon_token.nextToken(); } i++; } return true; } Code Sample 2: public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } }
00
Code Sample 1: public String getSHA1(String input) { byte[] output = null; try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes()); output = md.digest(); } catch (Exception e) { System.out.println("Exception: " + e); } return StringUtils.byte2hex(output); } Code Sample 2: private void copyTemplates(ProjectPath pPath) { String sourceAntPath = pPath.sourceAntPath(); final String moduleName = projectOperations.getFocusedTopLevelPackage().toString(); logger.info("Module Name: " + moduleName); String targetDirectory = pPath.canonicalFileSystemPath(projectOperations); logger.info("Moving into target Directory: " + targetDirectory); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } System.out.println("Target Directory: " + pPath.sourceAntPath()); String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); if (urls.isEmpty()) { logger.info("URLS are empty stopping..."); } for (URL url : urls) { logger.info("Stepping into " + url.toExternalForm()); String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); String targetFilename = targetDirectory + fileName; logger.info("Handling " + targetFilename); if (!fileManager.exists(targetFilename)) { try { logger.info("Copied file"); String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage()); logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations)); String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString(); input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage); input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage()); input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName()); input = input.replace("__ENTITY_NAME__", entityName); MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } }
11
Code Sample 1: public static byte[] ComputeForText(String ThisString) throws Exception { byte[] Result; MessageDigest MD5Hasher; MD5Hasher = MessageDigest.getInstance("MD5"); MD5Hasher.update(ThisString.replaceAll("\r", "").getBytes("iso-8859-1")); Result = MD5Hasher.digest(); return Result; } Code Sample 2: public static String login() throws Exception { if (sid == null) { String login = ROLAPClientAux.loadProperties().getProperty("user"); String password = ROLAPClientAux.loadProperties().getProperty("password"); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); String password2 = asHexString(md.digest()); String query = "/server/login?user=" + login + "&extern_password=" + password + "&password=" + password2; Vector<String> res = ROLAPClientAux.sendRequest(query); String vals[] = res.get(0).split(";"); sid = vals[0]; } return sid; }
11
Code Sample 1: private File uploadFile(InputStream inputStream, File file) { FileOutputStream fileOutputStream = null; try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileUtils.touch(file); fileOutputStream = new FileOutputStream(file); IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new FileOperationException("Failed to save uploaded image", e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { LOGGER.warn("Failed to close resources on uploaded file", e); } } return file; } Code Sample 2: static void linkBlocks(File from, File to, int oldLV) throws IOException { if (!from.isDirectory()) { if (from.getName().startsWith(COPY_FILE_PREFIX)) { IOUtils.copyBytes(new FileInputStream(from), new FileOutputStream(to), 16 * 1024, true); } else { if (oldLV >= PRE_GENERATIONSTAMP_LAYOUT_VERSION) { to = new File(convertMetatadataFileName(to.getAbsolutePath())); } HardLink.createHardLink(from, to); } return; } if (!to.mkdir()) throw new IOException("Cannot create directory " + to); String[] blockNames = from.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(BLOCK_FILE_PREFIX) || name.startsWith(COPY_FILE_PREFIX); } }); for (int i = 0; i < blockNames.length; i++) linkBlocks(new File(from, blockNames[i]), new File(to, blockNames[i]), oldLV); }
11
Code Sample 1: public void insertRight(final String right) throws IOException { try { Connection conn = null; boolean autoCommit = false; try { conn = pool.getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(true); final PreparedStatement insert = conn.prepareStatement("insert into rights (name) values (?)"); insert.setString(1, right); insert.executeUpdate(); } catch (Throwable t) { if (conn != null) conn.rollback(); throw new SQLException(t.toString()); } finally { if (conn != null) { conn.setAutoCommit(autoCommit); conn.close(); } } } catch (final SQLException sqle) { log.log(Level.SEVERE, sqle.toString(), sqle); throw new IOException(sqle.toString()); } } Code Sample 2: private void loadDDL() throws IOException { try { conn.createStatement().executeQuery("SELECT * FROM overrides").close(); } catch (SQLException e) { Statement stmt = null; if (!e.getMessage().matches(ERR_MISSING_TABLE)) { LOG.trace(SQL_ERROR, e); LOG.fatal(e); throw new IOException("Error on initial data store read", e); } String[] qry = { "CREATE TABLE overrides (id INT NOT NULL, title VARCHAR(255) NOT NULL, subtitle VARCHAR(255) NOT NULL, PRIMARY KEY(id))", "CREATE TABLE settings (var VARCHAR(32) NOT NULL, val VARCHAR(255) NOT NULL, PRIMARY KEY(var))", "INSERT INTO settings (var, val) VALUES ('schema', '1')" }; try { conn.setAutoCommit(false); stmt = conn.createStatement(); for (String q : qry) stmt.executeUpdate(q); conn.commit(); } catch (SQLException e2) { try { conn.rollback(); } catch (SQLException e3) { LOG.trace(SQL_ERROR, e3); LOG.error(e3); } LOG.trace(SQL_ERROR, e2); throw new IOException("Error initializing data store", e2); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e4) { LOG.trace(SQL_ERROR, e4); LOG.error(e4); throw new IOException("Unable to cleanup data store resources", e4); } } try { conn.setAutoCommit(true); } catch (SQLException e3) { LOG.trace(SQL_ERROR, e3); LOG.error(e3); throw new IOException("Unable to reset data store auto commit", e3); } } } return; }
00
Code Sample 1: public void load(URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("URL cannot be null."); } isFileBased = false; this.url = url; InputStream in = null; try { in = url.openStream(); load(in); } finally { if (in != null) { in.close(); } } } Code Sample 2: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } } Code Sample 2: public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
11
Code Sample 1: public static void copy(String pstrFileFrom, String pstrFileTo) { try { FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel(); FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
11
Code Sample 1: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } } Code Sample 2: public void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
00
Code Sample 1: @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getLocalPrincipal", args = { }) public final void test_getLocalPrincipal() { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getLocalPrincipal(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } try { HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); assertNull(con.getLocalPrincipal()); con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); assertNotNull("Local principal is null", con.getLocalPrincipal()); } catch (Exception e) { fail("Unexpected exception " + e); } } Code Sample 2: public void testDigest() { try { String myinfo = "我的测试信息"; MessageDigest alga = MessageDigest.getInstance("SHA-1"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); System.out.println("本信息摘要是:" + byte2hex(digesta)); MessageDigest algb = MessageDigest.getInstance("SHA-1"); algb.update(myinfo.getBytes()); if (MessageDigest.isEqual(digesta, algb.digest())) { System.out.println("信息检查正常"); } else { System.out.println("摘要不相同"); } } catch (NoSuchAlgorithmException ex) { System.out.println("非法摘要算法"); } }
00
Code Sample 1: public static String sendRequest(String urlstring) { URL url; String line; Log.i("DVBMonitor", "Please wait while receiving data from dvb..."); try { url = new URL(urlstring); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); if ((line = in.readLine()) != null) { return line; } else { return null; } } catch (Exception ex) { Log.e("DVBMonitor", ex.toString() + " while sending request to dvb"); return null; } } Code Sample 2: private void copyFile(URL from, File to) { try { InputStream is = from.openStream(); IOUtils.copy(is, new FileOutputStream(to)); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void insertQuotation(final String sText, final Source aSource) throws ConfigHandlerError, com.sun.star.uno.Exception { final XTextDocument xTextDocument = (XTextDocument) this.docController.getXInterface(XTextDocument.class, this.docController.getXFrame().getController().getModel()); final XMultiServiceFactory xMultiServiceFactory = (XMultiServiceFactory) this.docController.getXInterface(XMultiServiceFactory.class, xTextDocument); final XText xText = xTextDocument.getText(); final XTextViewCursor xTextViewCursor = ((XTextViewCursorSupplier) this.docController.getXInterface(XTextViewCursorSupplier.class, this.docController.getXFrame().getController())).getViewCursor(); final XTextRange xTextRange = xTextViewCursor.getStart(); if (aSource.getSourceType() == SourceType.QUOTE || aSource.getSourceType() == SourceType.WEBQUOTE || aSource.getSourceType() == SourceType.WEBQUOTE) { final XPropertySet xQuoteProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xTextViewCursor); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String("Quotations")); } xQuoteProps.setPropertyValue("CharStyleName", new String("Citation")); final Object aBookmark = xMultiServiceFactory.createInstance("com.sun.star.text.Bookmark"); this.sourceUtils.setNameToObject(aBookmark, this.docController.getLanguageController().__("Quote: ") + aSource.getShortinfo()); final XTextContent xTextContent = (XTextContent) this.docController.getXInterface(XTextContent.class, aBookmark); xText.insertTextContent(xTextRange, xTextContent, false); this.sourceUtils.insertBibliographyEntry(xMultiServiceFactory, xTextRange, aSource, sText); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String(this.docController.getLanguageController().__("Default"))); } xQuoteProps.setPropertyValue("CharStyleName", new String(this.docController.getLanguageController().__("Default"))); } else if (aSource.getSourceType() == SourceType.IMAGE || aSource.getSourceType() == SourceType.TABLE) { xText.insertControlCharacter(xTextRange, ControlCharacter.PARAGRAPH_BREAK, false); final XTextFrame xFrame = this.sourceUtils.getTextFrame(aSource.getShortinfo(), xMultiServiceFactory); xText.insertTextContent(xTextRange, xFrame, false); final XText xFrameText = xFrame.getText(); final XTextCursor xFrameCursor = xFrameText.createTextCursor(); final Size aNewSize = new Size(); XPropertySet xBaseFrameProps = null; final Size aPageTextAreaSize = this.sourceUtils.getPageTextAreaSize(xTextDocument, xTextViewCursor); if (aSource.getSourceType() == SourceType.IMAGE) { try { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption illustration: ") + aSource.getShortinfo()); final XNameContainer xBitmapContainer = (XNameContainer) this.docController.getXInterface(XNameContainer.class, xMultiServiceFactory.createInstance("com.sun.star.drawing.BitmapTable")); final XTextContent xImage = (XTextContent) this.docController.getXInterface(XTextContent.class, xMultiServiceFactory.createInstance("com.sun.star.text.TextGraphicObject")); this.sourceUtils.setNameToObject(xImage, this.docController.getLanguageController().__("Illustration: ") + aSource.getShortinfo()); final String graphicURL = this.docController.getPathUtils().getFileURLFromSystemPath(((Image) aSource).getFile().getPath(), ((Image) aSource).getFile().getPath()); xBaseFrameProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xImage); xBaseFrameProps.setPropertyValue("AnchorType", com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH); xBaseFrameProps.setPropertyValue("GraphicURL", graphicURL); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(graphicURL.getBytes(), 0, graphicURL.length()); final String internalName = new BigInteger(1, md.digest()).toString(16); xBitmapContainer.insertByName(internalName, graphicURL); final String internalURL = (String) (xBitmapContainer.getByName(internalName)); xBaseFrameProps.setPropertyValue("GraphicURL", internalURL); float imageRatio = (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height / (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width; final Size aUsedAreaSize = new Size(this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width * 26, this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height * 26); if (aUsedAreaSize.Width >= aPageTextAreaSize.Width) { aNewSize.Width = aPageTextAreaSize.Width; aNewSize.Height = (int) (aPageTextAreaSize.Width * imageRatio); } else { aNewSize.Width = aUsedAreaSize.Width; aNewSize.Height = aUsedAreaSize.Height; } xFrameText.insertTextContent(xFrameCursor, xImage, false); xBitmapContainer.removeByName(internalName); } catch (final NoSuchAlgorithmException e) { new ASTError(e).severe(); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Illustration"), xMultiServiceFactory); } else if (aSource.getSourceType() == SourceType.TABLE) { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption table: ") + aSource.getShortinfo()); xBaseFrameProps = this.sourceUtils.createTextEmbeddedObjectCalc(xMultiServiceFactory); this.sourceUtils.setNameToObject(xBaseFrameProps, this.docController.getLanguageController().__("Table: ") + aSource.getShortinfo()); xFrameText.insertTextContent(xFrameCursor, (XTextContent) this.docController.getXInterface(XTextContent.class, xBaseFrameProps), false); final XEmbeddedObjectSupplier2 xEmbeddedObjectSupplier = (XEmbeddedObjectSupplier2) this.docController.getXInterface(XEmbeddedObjectSupplier2.class, xBaseFrameProps); final XEmbeddedObject xEmbeddedObject = xEmbeddedObjectSupplier.getExtendedControlOverEmbeddedObject(); long nAspect = xEmbeddedObjectSupplier.getAspect(); final Size aVisualAreaSize = xEmbeddedObject.getVisualAreaSize(nAspect); final XComponent xComponent = xEmbeddedObjectSupplier.getEmbeddedObject(); XSpreadsheets xSpreadsheets = ((XSpreadsheetDocument) this.docController.getXInterface(XSpreadsheetDocument.class, xComponent)).getSheets(); final XIndexAccess xIndexAccess = (XIndexAccess) this.docController.getXInterface(XIndexAccess.class, xSpreadsheets); final XSpreadsheet xSpreadsheet = (XSpreadsheet) this.docController.getXInterface(XSpreadsheet.class, xIndexAccess.getByIndex(0)); final XSheetLinkable xSheetLinkable = (XSheetLinkable) this.docController.getXInterface(XSheetLinkable.class, xSpreadsheet); xSheetLinkable.link(this.docController.getPathUtils().getFileURLFromSystemPath(((Table) aSource).getFile().getPath(), ((Table) aSource).getFile().getPath()), "", "", "", com.sun.star.sheet.SheetLinkMode.NORMAL); final CellRangeAddress aUsedArea = this.sourceUtils.getUsedArea(xSpreadsheet); final Size aUsedAreaSize = this.sourceUtils.calcCellRangeSize(xSpreadsheets, aUsedArea); if ((aUsedAreaSize.Width != aVisualAreaSize.Width) || (aUsedAreaSize.Height != aVisualAreaSize.Height)) { aNewSize.Height = (aUsedAreaSize.Height > aPageTextAreaSize.Height) ? aPageTextAreaSize.Height : aUsedAreaSize.Height; aNewSize.Width = (aUsedAreaSize.Width > aPageTextAreaSize.Width) ? aPageTextAreaSize.Width : aUsedAreaSize.Width; xEmbeddedObject.setVisualAreaSize(nAspect, aNewSize); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Table"), xMultiServiceFactory); } xBaseFrameProps.setPropertyValue("Width", aNewSize.Width); xBaseFrameProps.setPropertyValue("Height", aNewSize.Height); final XShape xShape = (XShape) this.docController.getXInterface(XShape.class, xFrame); xShape.setSize(aNewSize); } final XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier) this.docController.getXInterface(XTextFieldsSupplier.class, xMultiServiceFactory); final XRefreshable xRefreshable = (XRefreshable) this.docController.getXInterface(XRefreshable.class, xTextFieldsSupplier.getTextFields()); xRefreshable.refresh(); } Code Sample 2: protected String getGraphPath(String name) throws ServletException { String hash; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(name.getBytes()); hash = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to hash file name: " + e); } File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); return tempDir.getAbsolutePath() + File.separatorChar + hash; }
00
Code Sample 1: private void runGetVendorProfile() { DataStorage.clearVendorProfile(); GenericUrl url = new GoogleUrl(EnterpriseMarketplaceUrl.generateVendorProfileUrl()); VendorProfile vendorProfile = null; try { HttpRequest request = requestFactory.buildGetRequest(url); request.addParser(jsonHttpParser); request.readTimeout = readTimeout; HttpResponse response = request.execute(); vendorProfile = response.parseAs(VendorProfile.class); if (vendorProfile != null && vendorProfile.vendorId != null && vendorProfile.email != null && !StringUtilities.isEmpty(vendorProfile.email)) { DataStorage.setVendorProfile(vendorProfile); operationStatus = true; } response.getContent().close(); } catch (IOException e) { AppsMarketplacePluginLog.logError(e); } } Code Sample 2: private void sendActionPerformed(java.awt.event.ActionEvent evt) { if (name.getText().length() < 3) { JOptionPane.showMessageDialog(comment, "Too short name (at least 3)"); return; } if (comment.getText().length() < 10) { JOptionPane.showMessageDialog(comment, "Too short comment (at least 10)"); return; } Thread t = new Thread(new Runnable() { public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } } }); t.start(); }
11
Code Sample 1: public static String translate(String s, String type) { try { String result = null; URL url = new URL("http://www.excite.co.jp/world/english/"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("before=" + URLEncoder.encode(s, "SJIS") + "&wb_lp="); out.print(type); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "SJIS")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("name=\"after\""); if (textPos >= 0) { int ltrPos = inputLine.indexOf(">", textPos + 11); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 1); if (closePos >= 0) { result = inputLine.substring(ltrPos + 1, closePos); break; } else { result = inputLine.substring(ltrPos + 1); break; } } } } in.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
00
Code Sample 1: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } Code Sample 2: private String protectMarkup(String content, String markupRegex, String replaceSource, String replaceTarget) { Matcher matcher = Pattern.compile(markupRegex, Pattern.MULTILINE | Pattern.DOTALL).matcher(content); StringBuffer result = new StringBuffer(); while (matcher.find()) { String protectedMarkup = matcher.group(); protectedMarkup = protectedMarkup.replaceAll(replaceSource, replaceTarget); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(protectedMarkup.getBytes("UTF-8")); String hash = bytesToHash(digest.digest()); matcher.appendReplacement(result, hash); c_protectionMap.put(hash, protectedMarkup); m_hashList.add(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } matcher.appendTail(result); return result.toString(); }
00
Code Sample 1: public static String getMD5(String text) { if (text == null) { return null; } String result = null; try { MessageDigest md5 = MessageDigest.getInstance(ALG_MD5); md5.update(text.getBytes(ENCODING)); result = "" + new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } Code Sample 2: public static LinkedList Import(String url) throws Exception { LinkedList data = new LinkedList(); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String csvLine; while ((csvLine = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(csvLine, ","); CSVData cd = new CSVData(); st.nextToken(); st.nextToken(); cd.matrNumber = Integer.parseInt(st.nextToken().trim()); cd.fName = st.nextToken().trim(); cd.lName = st.nextToken().trim(); cd.email = st.nextToken().trim(); cd.stdyPath = st.nextToken().trim(); cd.sem = Integer.parseInt(st.nextToken().trim()); data.add(cd); } in.close(); return data; }
11
Code Sample 1: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; String review = request.getParameter("review"); String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String inforId = request.getParameter("inforId"); request.setAttribute("id", inforId); String str_postFIX = ""; int i_p = 0; if (null == review) { FormFile file = vo.getFile(); if (file != null) { 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(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); String fullPath = realpath + "attach/" + strAppend + str_postFIX; 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(); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); return "editsave"; } else { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); FormFile file = vo.getFile(); FormFile file2 = vo.getFile2(); FormFile file3 = vo.getFile3(); t_infor_review newreview = new t_infor_review(); String content = request.getParameter("content"); newreview.setContent(content); if (null != inforId) newreview.setInfor_id(Integer.parseInt(inforId)); newreview.setInsert_day(new Date()); UserDetails user = LoginUtils.getLoginUser(request); newreview.setCreate_name(user.getUsercode()); if (null != file.getFileName() && !"".equals(file.getFileName())) { newreview.setAttachname1(file.getFileName()); String strAppend1 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); newreview.setAttachfullname1(realpath + "attach/" + strAppend1 + str_postFIX); saveFile(file.getInputStream(), realpath + "attach/" + strAppend1 + str_postFIX); } if (null != file2.getFileName() && !"".equals(file2.getFileName())) { newreview.setAttachname2(file2.getFileName()); String strAppend2 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file2.getFileName().lastIndexOf("."); str_postFIX = file2.getFileName().substring(i_p, file2.getFileName().length()); newreview.setAttachfullname2(realpath + "attach/" + strAppend2 + str_postFIX); saveFile(file2.getInputStream(), realpath + "attach/" + strAppend2 + str_postFIX); } if (null != file3.getFileName() && !"".equals(file3.getFileName())) { newreview.setAttachname3(file3.getFileName()); String strAppend3 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file3.getFileName().lastIndexOf("."); str_postFIX = file3.getFileName().substring(i_p, file3.getFileName().length()); newreview.setAttachfullname3(realpath + "attach/" + strAppend3 + str_postFIX); saveFile(file3.getInputStream(), realpath + "attach/" + strAppend3 + str_postFIX); } t_infor_review_EditMap reviewEdit = new t_infor_review_EditMap(); reviewEdit.add(newreview); request.setAttribute("review", "1"); return "aftersave"; } } Code Sample 2: public static PortalConfig install(File xml, File dir) throws IOException, ConfigurationException { if (!dir.exists()) { log.info("Creating directory {}", dir); dir.mkdirs(); } if (!xml.exists()) { log.info("Installing default configuration to {}", xml); OutputStream output = new FileOutputStream(xml); try { InputStream input = ResourceLoader.open("res://" + PORTAL_CONFIG_XML); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { output.close(); } } return create(xml, dir); }
00
Code Sample 1: public static String MD5(String text) { try { 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); } catch (Exception e) { System.out.println(e.toString()); } return null; } Code Sample 2: private List<String> readUrl(URL url) throws IOException { List<String> lines = new ArrayList<String>(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { lines.add(str); } in.close(); return lines; }
11
Code Sample 1: static void linkBlocks(File from, File to, int oldLV) throws IOException { if (!from.isDirectory()) { if (from.getName().startsWith(COPY_FILE_PREFIX)) { IOUtils.copyBytes(new FileInputStream(from), new FileOutputStream(to), 16 * 1024, true); } else { if (oldLV >= PRE_GENERATIONSTAMP_LAYOUT_VERSION) { to = new File(convertMetatadataFileName(to.getAbsolutePath())); } HardLink.createHardLink(from, to); } return; } if (!to.mkdir()) throw new IOException("Cannot create directory " + to); String[] blockNames = from.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(BLOCK_FILE_PREFIX) || name.startsWith(COPY_FILE_PREFIX); } }); for (int i = 0; i < blockNames.length; i++) linkBlocks(new File(from, blockNames[i]), new File(to, blockNames[i]), oldLV); } Code Sample 2: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) abort("FileCopy: no such source file: " + from_file.getName()); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_file.getName()); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_file.getName()); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_file.getName()); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { e.printStackTrace(); } } if (to != null) { try { to.close(); } catch (IOException e) { e.printStackTrace(); } } } }