label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
private void fetchAvailable(ProgressObserver po) { if (po == null) throw new IllegalArgumentException("the progress observer can't be null"); if (availables == null) availables = new ArrayList<Dictionary>(); else availables.clear(); if (installed == null) initInstalled(); File home = SpellCheckPlugin.getHomeDir(jEdit.getActiveView()); File target = new File(home, "available.lst"); try { boolean skipDownload = false; if (target.exists()) { long modifiedDate = target.lastModified(); Calendar c = Calendar.getInstance(); c.setTimeInMillis(modifiedDate); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.HOUR, -1); skipDownload = yesterday.before(c); } String enc = null; if (!skipDownload) { URL available_url = new URL(jEdit.getProperty(OOO_DICTS_PROP) + "available.lst"); URLConnection connect = available_url.openConnection(); connect.connect(); InputStream is = connect.getInputStream(); po.setMaximum(connect.getContentLength()); OutputStream os = new FileOutputStream(target); boolean copied = IOUtilities.copyStream(po, is, os, true); if (!copied) { Log.log(Log.ERROR, HunspellDictsManager.class, "Unable to download " + available_url.toString()); GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { "Unable to download file " + available_url.toString() }); availables = null; if (target.exists()) target.delete(); return; } IOUtilities.closeQuietly(os); enc = connect.getContentEncoding(); } FileInputStream fis = new FileInputStream(target); Reader r; if (enc != null) { try { r = new InputStreamReader(fis, enc); } catch (UnsupportedEncodingException uee) { r = new InputStreamReader(fis, "UTF-8"); } } else { r = new InputStreamReader(fis, "UTF-8"); } BufferedReader br = new BufferedReader(r); for (String line = br.readLine(); line != null; line = br.readLine()) { Dictionary d = parseLine(line); if (d != null) { int ind = installed.indexOf(d); if (ind == -1) { d.installed = false; availables.add(d); } else { Dictionary id = installed.get(ind); if (!skipDownload) { Date lmd = fetchLastModifiedDate(id.archiveName); if (lmd != null) { id.lastModified = lmd; } } } } } IOUtilities.closeQuietly(fis); } catch (IOException ioe) { if (ioe instanceof UnknownHostException) { GUIUtilities.error(null, "spell-check-hunspell-error-unknownhost", new String[] { ioe.getMessage() }); } else { GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { ioe.getMessage() }); } ioe.printStackTrace(); if (target.exists()) target.delete(); } }
Code Sample 2:
public static void downloadFromUrl(URL url, String localFilename, String userAgent) throws IOException { InputStream is = null; FileOutputStream fos = null; System.setProperty("java.net.useSystemProxies", "true"); try { URLConnection urlConn = url.openConnection(); if (userAgent != null) { urlConn.setRequestProperty("User-Agent", userAgent); } is = urlConn.getInputStream(); fos = new FileOutputStream(localFilename); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } }
|
11
|
Code Sample 1:
private static void zip(ZipArchiveOutputStream zos, File efile, String base) throws IOException { if (efile.isDirectory()) { File[] lf = efile.listFiles(); base = base + File.separator + efile.getName(); for (File file : lf) { zip(zos, file, base); } } else { ZipArchiveEntry entry = new ZipArchiveEntry(efile, base + File.separator + efile.getName()); zos.setEncoding("utf-8"); zos.putArchiveEntry(entry); InputStream is = new FileInputStream(efile); IOUtils.copy(is, zos); is.close(); zos.closeArchiveEntry(); } }
Code Sample 2:
protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
|
00
|
Code Sample 1:
public static synchronized BaseFont getL2BaseFont() { if (l2baseFont == null) { final ConfigProvider conf = ConfigProvider.getInstance(); try { final ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); String fontPath = conf.getNotEmptyProperty("font.path", null); String fontName; String fontEncoding; InputStream tmpIs; if (fontPath != null) { fontName = conf.getNotEmptyProperty("font.name", null); if (fontName == null) { fontName = new File(fontPath).getName(); } fontEncoding = conf.getNotEmptyProperty("font.encoding", null); if (fontEncoding == null) { fontEncoding = BaseFont.WINANSI; } tmpIs = new FileInputStream(fontPath); } else { fontName = Constants.L2TEXT_FONT_NAME; fontEncoding = BaseFont.IDENTITY_H; tmpIs = FontUtils.class.getResourceAsStream(Constants.L2TEXT_FONT_PATH); } IOUtils.copy(tmpIs, tmpBaos); tmpIs.close(); tmpBaos.close(); l2baseFont = BaseFont.createFont(fontName, fontEncoding, BaseFont.EMBEDDED, BaseFont.CACHED, tmpBaos.toByteArray(), null); } catch (Exception e) { e.printStackTrace(); try { l2baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); } catch (Exception ex) { } } } return l2baseFont; }
Code Sample 2:
public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,nextval('pilot_id_seq'))"); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); if (pilotData.id != 0) { psta.setInt(19, pilotData.id); } psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } }
|
00
|
Code Sample 1:
private void writeJar() { try { File outJar = new File(currentProjectDir + DEPLOYDIR + fileSeparator + currentProjectName + ".jar"); jarSize = (int) outJar.length(); File tempJar = File.createTempFile("hipergps" + currentProjectName, ".jar"); tempJar.deleteOnExit(); File preJar = new File(currentProjectDir + "/res/wtj2me.jar"); JarInputStream preJarInStream = new JarInputStream(new FileInputStream(preJar)); Manifest mFest = preJarInStream.getManifest(); java.util.jar.Attributes atts = mFest.getMainAttributes(); if (hiperGeoId != null) { atts.putValue("hiperGeoId", hiperGeoId); } jad.updateAttributes(atts); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(tempJar), mFest); byte[] buffer = new byte[WalkingtoolsInformation.BUFFERSIZE]; JarEntry jarEntry = null; while ((jarEntry = preJarInStream.getNextJarEntry()) != null) { if (jarEntry.getName().contains("net/") || jarEntry.getName().contains("org/")) { try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } int read; while ((read = preJarInStream.read(buffer)) != -1) { jarOutStream.write(buffer, 0, read); } jarOutStream.closeEntry(); } } File[] icons = { new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "icon_" + WalkingtoolsInformation.MEDIAUUID + ".png"), new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "loaderIcon_" + WalkingtoolsInformation.MEDIAUUID + ".png"), new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "mygps_" + WalkingtoolsInformation.MEDIAUUID + ".png") }; for (int i = 0; i < icons.length; i++) { jarEntry = new JarEntry("img/" + icons[i].getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(icons[i]); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } for (int i = 0; i < imageFiles.size(); i++) { jarEntry = new JarEntry("img/" + imageFiles.get(i).getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(imageFiles.get(i)); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } for (int i = 0; i < audioFiles.size(); i++) { jarEntry = new JarEntry("audio/" + audioFiles.get(i).getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(audioFiles.get(i)); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } File gpx = new File(currentProjectDir + WalkingtoolsInformation.GPXDIR + "/hipergps.gpx"); jarEntry = new JarEntry("gpx/" + gpx.getName()); jarOutStream.putNextEntry(jarEntry); FileInputStream in = new FileInputStream(gpx); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); jarOutStream.flush(); jarOutStream.close(); jarSize = (int) tempJar.length(); preJarInStream = new JarInputStream(new FileInputStream(tempJar)); mFest = preJarInStream.getManifest(); atts = mFest.getMainAttributes(); atts.putValue("MIDlet-Jar-Size", "" + jarSize + 1); jarOutStream = new JarOutputStream(new FileOutputStream(outJar), mFest); while ((jarEntry = preJarInStream.getNextJarEntry()) != null) { try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } int read; while ((read = preJarInStream.read(buffer)) != -1) { jarOutStream.write(buffer, 0, read); } jarOutStream.closeEntry(); } jarOutStream.flush(); preJarInStream.close(); jarOutStream.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public synchronized void downloadTile(TileNumber tn) { try { Bitmap tile = getMapFromSdCache(tn); if (tile == null) { URL url = new URL("http://tile.openstreetmap.org/" + tn.getZoom() + "/" + tn.getX() + "/" + tn.getY() + ".png"); tile = BitmapFactory.decodeStream(url.openStream()); File sdCardPath = Environment.getExternalStorageDirectory(); Log.d(ctx.getResources().getString(open.gps.gopens.R.string.TEST), "Path to SD :: " + sdCardPath.getAbsolutePath()); File dir = new File(sdCardPath + ctx.getResources().getString(open.gps.gopens.R.string.CACHE_PATH) + tn.getZoom() + "/" + tn.getX() + "/"); dir.mkdirs(); File imgFile = new File(dir.getAbsolutePath() + "/" + tn.getY() + ".png"); imgFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(imgFile); tile.compress(Bitmap.CompressFormat.PNG, 100, fOut); } cacheManager.put(tn.toString(), tile); setChanged(); notifyObservers(); Log.d("OBS", "OBS : Notify"); } catch (MalformedURLException e) { Log.e("Error", e.getMessage()); } catch (IOException e) { Log.e("Error", e.getMessage()); } }
|
11
|
Code Sample 1:
public void testBeAbleToDownloadAndUpload() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); ensure.that(buffer.toByteArray()).eq(new byte[] { 1, 2, 3 }); }
Code Sample 2:
private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
|
11
|
Code Sample 1:
public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException { String id = CryptSHA1.genPhotoID(userLogin, title); String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf(".")); String destination = basePathImage + id + extension; FileInputStream fis = new FileInputStream(pathToPhoto); FileOutputStream fos = new FileOutputStream(destination); FileChannel fci = fis.getChannel(); FileChannel fco = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int read = fci.read(buffer); if (read == -1) break; buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); fco.close(); fos.close(); fis.close(); ImageIcon image; ImageIcon thumb; String destinationThumb = basePathImage + "thumb/" + id + extension; image = new ImageIcon(destination); int maxSize = 150; int origWidth = image.getIconWidth(); int origHeight = image.getIconHeight(); if (origWidth > origHeight) { thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH)); } else { thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH)); } BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(thumb.getImage(), 0, 0, null); try { ImageIO.write(bi, "JPG", new File(destinationThumb)); } catch (IOException ioe) { System.out.println("Error occured saving thumbnail"); } Photo photo = new Photo(id); photo.setTitle(title); photo.basePathImage = basePathImage; return photo; }
Code Sample 2:
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[8192]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
|
11
|
Code Sample 1:
public static void perform(ChangeSet changes, ArchiveInputStream in, ArchiveOutputStream out) throws IOException { ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { System.out.println(entry.getName()); boolean copy = true; for (Iterator it = changes.asSet().iterator(); it.hasNext(); ) { Change change = (Change) it.next(); if (change.type() == ChangeSet.CHANGE_TYPE_DELETE) { DeleteChange delete = ((DeleteChange) change); if (entry.getName() != null && entry.getName().equals(delete.targetFile())) { copy = false; } } } if (copy) { System.out.println("Copy: " + entry.getName()); long size = entry.getSize(); out.putArchiveEntry(entry); IOUtils.copy((InputStream) in, out, (int) size); out.closeArchiveEntry(); } System.out.println("---"); } out.close(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public ActionResponse executeAction(ActionRequest request) throws Exception { BufferedReader in = null; try { CurrencyEntityManager em = new CurrencyEntityManager(); String id = (String) request.getProperty("ID"); CurrencyMonitor cm = getCurrencyMonitor(em, Long.valueOf(id)); String code = cm.getCode(); if (code == null || code.length() == 0) code = DEFAULT_SYMBOL; String tmp = URL.replace("@", code); ActionResponse resp = new ActionResponse(); URL url = new URL(tmp); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int status = conn.getResponseCode(); if (status == 200) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder value = new StringBuilder(); while (true) { String line = in.readLine(); if (line == null) break; value.append(line); } cm.setLastUpdateValue(new BigDecimal(value.toString())); cm.setLastUpdateTs(new Date()); em.updateCurrencyMonitor(cm); resp.addResult("CURRENCYMONITOR", cm); } else { resp.setErrorCode(ActionResponse.GENERAL_ERROR); resp.setErrorMessage("HTTP Error [" + status + "]"); } return resp; } catch (Exception e) { String st = MiscUtils.stackTrace2String(e); logger.error(st); throw e; } finally { if (in != null) { in.close(); } } }
Code Sample 2:
public static String exchangeForSessionToken(String protocol, String domain, String onetimeUseToken, PrivateKey key) throws IOException, GeneralSecurityException, AuthenticationException { String sessionUrl = getSessionTokenUrl(protocol, domain); URL url = new URL(sessionUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); String header = formAuthorizationHeader(onetimeUseToken, key, url, "GET"); httpConn.setRequestProperty("Authorization", header); if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AuthenticationException(httpConn.getResponseCode() + ": " + httpConn.getResponseMessage()); } String body = IOUtils.toString(httpConn.getInputStream()); Map parsedTokens = StringUtils.string2Map(body, "\n", "=", true); parsedTokens = StringUtils.lowercaseKeys(parsedTokens); return (String) parsedTokens.get("token"); }
|
00
|
Code Sample 1:
private void downloadPage(final URL url, final File file) { try { long size = 0; final byte[] buffer = new byte[BotUtil.BUFFER_SIZE]; final File tempFile = new File(file.getParentFile(), "temp.tmp"); int length; int lastUpdate = 0; FileOutputStream fos = new FileOutputStream(tempFile); final InputStream is = url.openStream(); do { length = is.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Downloading... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); if (url.toString().toLowerCase().endsWith(".gz")) { final FileInputStream fis = new FileInputStream(tempFile); final GZIPInputStream gis = new GZIPInputStream(fis); fos = new FileOutputStream(file); size = 0; lastUpdate = 0; do { length = gis.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Uncompressing... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); fis.close(); gis.close(); tempFile.delete(); } else { file.delete(); tempFile.renameTo(file); } } catch (final IOException e) { throw new AnalystError(e); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
private List<String> createProjectInfoFile() throws SocketException, IOException { FTPClient client = new FTPClient(); Set<String> projects = new HashSet<String>(); client.connect("ftp.drupal.org"); System.out.println("Connected to ftp.drupal.org"); System.out.println(client.getReplyString()); boolean loggedIn = client.login("anonymous", "[email protected]"); if (loggedIn) { FTPFile[] files = client.listFiles("pub/drupal/files/projects"); for (FTPFile file : files) { String name = file.getName(); Pattern p = Pattern.compile("([a-zAZ_]*)-(\\d.x)-(.*)"); Matcher m = p.matcher(name); if (m.matches()) { String projectName = m.group(1); String version = m.group(2); if (version.equals("6.x")) { projects.add(projectName); } } } } List<String> projectList = new ArrayList<String>(); for (String project : projects) { projectList.add(project); } Collections.sort(projectList); return projectList; }
Code Sample 2:
void loadImage(final int runnumber, final String surl, final StatusCallback status) { Runnable run = new Runnable() { public void run() { try { if (sync == SyncType.SyncSpaced || sync == SyncType.Spaced) { Thread.sleep(spaceMillis); } URL url = new URL(surl + "&requestId=" + runnumber); long t0 = System.currentTimeMillis(); InputStream in = url.openStream(); transfer(in, new FileOutputStream(new File(outputFolder, "" + runnumber + ".png"))); BufferedImage image = ImageIO.read(new File(outputFolder, "" + runnumber + ".png")); status.score(runnumber, System.currentTimeMillis() - t0); ImageIO.write(image, "png", new FileOutputStream(new File(outputFolder, "" + runnumber + ".png"))); if (false) { int whiteCount = 0; for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { whiteCount += image.getRGB(i, j) == -1 ? 1 : 0; } } System.err.println("##" + runnumber + "#: " + whiteCount); if (whiteCount < 227564) { System.err.println("whiteCount fails!!!!"); System.err.println("whiteCount fails!!!!"); System.exit(0); } } } catch (Exception ex) { System.err.println("##" + runnumber + "#: Exception!!! ###"); ex.printStackTrace(); status.score(runnumber, -999); } } }; if (sync == SyncType.SyncSpaced || sync == SyncType.Sync) { run.run(); } else { new Thread(run).start(); } }
|
11
|
Code Sample 1:
public void greatestIncrease(int maxIterations) { double[] increase = new double[numModels]; int[] id = new int[numModels]; Model md = new Model(); double oldPerf = 1; for (int i = 0; i < numModels; i++) { md.addModel(models[i], false); increase[i] = oldPerf - md.getLoss(); id[i] = i; oldPerf = md.getLoss(); } for (int i = 0; i < numModels; i++) { for (int j = 0; j < numModels - 1 - i; j++) { if (increase[j] < increase[j + 1]) { double increasetemp = increase[j]; int temp = id[j]; increase[j] = increase[j + 1]; id[j] = id[j + 1]; increase[j + 1] = increasetemp; id[j + 1] = temp; } } } for (int i = 0; i < maxIterations; i++) { addToEnsemble(models[id[i]]); if (report) ensemble.report(models[id[i]].getName(), allSets); updateBestModel(); } }
Code Sample 2:
public void bubblesort(String filenames[]) { for (int i = filenames.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { String temp; if (filenames[j].compareTo(filenames[j + 1]) > 0) { temp = filenames[j]; filenames[j] = filenames[j + 1]; filenames[j + 1] = temp; } } } }
|
11
|
Code Sample 1:
private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
@Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } }
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; }
|
11
|
Code Sample 1:
private String extractFileFromZip(ZipFile zip, String fileName) throws IOException { String contents = null; ZipEntry entry = zip.getEntry(fileName); if (entry != null) { InputStream input = zip.getInputStream(entry); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, buffer); contents = buffer.toString(); } return contents; }
Code Sample 2:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
|
11
|
Code Sample 1:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } return hexString.toString(); }
Code Sample 2:
public static 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; }
|
00
|
Code Sample 1:
public static String downloadJar(URL url) throws IOException { String localFile = null; char[] buf = new char[4096]; int num; localFile = Settings.getFreeTsUserPath() + "lib" + Settings.SLASH + getURLFileName(url); DebugDialog.print("Downloading jar-file " + url + " to " + localFile + ".", 4); InputStreamReader in = new InputStreamReader(url.openStream()); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(localFile)); do { num = in.read(buf, 0, 4096); if (num > 0) { out.write(buf, 0, num); } } while (num > 0); in.close(); out.close(); return localFile; }
Code Sample 2:
public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } }
|
00
|
Code Sample 1:
@Override protected Integer doInBackground() throws Exception { int numOfRows = 0; combinationMap = new HashMap<AnsweredQuestion, Integer>(); combinationMapReverse = new HashMap<Integer, AnsweredQuestion>(); LinkedHashSet<AnsweredQuestion> answeredQuestionSet = new LinkedHashSet<AnsweredQuestion>(); LinkedHashSet<Integer> studentSet = new LinkedHashSet<Integer>(); final String delimiter = ";"; final String typeToProcess = "F"; String line; String[] chunks = new String[9]; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); numOfRows++; if (chunks[2].equals(typeToProcess)) { answeredQuestionSet.add(new AnsweredQuestion(chunks[4], chunks[5])); studentSet.add(new Integer(chunks[0])); } } in.close(); int i = 0; Integer I; for (AnsweredQuestion pair : answeredQuestionSet) { I = new Integer(i++); combinationMap.put(pair, I); combinationMapReverse.put(I, pair); } matrix = new SparseObjectMatrix2D(answeredQuestionSet.size(), studentSet.size()); int lastStudentNumber = -1; AnsweredQuestion pair; in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); pair = null; if (chunks[2].equals(typeToProcess)) { if (Integer.parseInt(chunks[0]) != lastStudentNumber) { lastStudentNumber++; } pair = new AnsweredQuestion(chunks[4], chunks[5]); if (combinationMap.containsKey(pair)) { matrix.setQuick(combinationMap.get(pair), lastStudentNumber, Boolean.TRUE); } } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } supportVector = new int[combinationMap.size()]; ObjectMatrix1D row = null; for (int i = 0; i < combinationMap.size(); i++) { row = matrix.viewRow(i); int sum = 0; for (int k = 0; k < row.size(); k++) { if (row.getQuick(k) != null && row.getQuick(k).equals(Boolean.TRUE)) { sum++; } } supportVector[i] = sum; } applet.combinationMap = this.combinationMap; applet.combinationMapReverse = this.combinationMapReverse; applet.matrix = this.matrix; applet.supportVector = supportVector; System.out.println("data loaded."); return null; }
Code Sample 2:
public static Image getPluginImage(Object plugin, 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:
private boolean processar(int iCodProd) { String sSQL = null; String sSQLCompra = null; String sSQLInventario = null; String sSQLVenda = null; String sSQLRMA = null; String sSQLOP = null; String sSQLOP_SP = null; String sWhere = null; String sProd = null; String sWhereCompra = null; String sWhereInventario = null; String sWhereVenda = null; String sWhereRMA = null; String sWhereOP = null; String sWhereOP_SP = null; PreparedStatement ps = null; ResultSet rs = null; boolean bOK = false; try { try { sWhere = ""; sProd = ""; if (cbTudo.getVlrString().equals("S")) sProd = "[" + iCodProd + "] "; if (!(txtDataini.getVlrString().equals(""))) { sWhere = " AND DTMOVPROD >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; } sSQL = "DELETE FROM EQMOVPROD WHERE " + "CODEMP=? AND CODPROD=?" + sWhere; state(sProd + "Limpando movimenta��es desatualizadas..."); ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); if ((txtDataini.getVlrString().equals(""))) { sSQL = "UPDATE EQPRODUTO SET SLDPROD=0 WHERE " + "CODEMP=? AND CODPROD=?"; ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); state(sProd + "Limpando saldos..."); sSQL = "UPDATE EQSALDOPROD SET SLDPROD=0 WHERE CODEMP=? AND CODPROD=?"; ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); state(sProd + "Limpando saldos..."); } bOK = true; } catch (SQLException err) { Funcoes.mensagemErro(null, "Erro ao limpar estoques!\n" + err.getMessage(), true, con, err); } if (bOK) { bOK = false; if (!txtDataini.getVlrString().equals("")) { sWhereCompra = " AND C.DTENTCOMPRA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereInventario = " AND I.DATAINVP >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereVenda = " AND V.DTEMITVENDA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereRMA = " AND RMA.DTAEXPRMA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereOP = " AND O.DTFABROP >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereOP_SP = " AND O.DTSUBPROD >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; } else { sWhereCompra = ""; sWhereInventario = ""; sWhereVenda = ""; sWhereRMA = ""; sWhereOP = ""; sWhereOP_SP = ""; } sSQLInventario = "SELECT 'A' TIPOPROC, I.CODEMPPD, I.CODFILIALPD, I.CODPROD," + "I.CODEMPLE, I.CODFILIALLE, I.CODLOTE," + "I.CODEMPTM, I.CODFILIALTM, I.CODTIPOMOV," + "I.CODEMP, I.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "I.CODINVPROD CODMASTER, I.CODINVPROD CODITEM, " + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT ,CAST(NULL AS CHAR(4)) CODNAT," + "I.DATAINVP DTPROC, I.CODINVPROD DOCPROC,'N' FLAG," + "I.QTDINVP QTDPROC, I.PRECOINVP CUSTOPROC, " + "I.CODEMPAX, I.CODFILIALAX, I.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM EQINVPROD I " + "WHERE I.CODEMP=? AND I.CODPROD = ?" + sWhereInventario; sSQLCompra = "SELECT 'C' TIPOPROC, IC.CODEMPPD, IC.CODFILIALPD, IC.CODPROD," + "IC.CODEMPLE, IC.CODFILIALLE, IC.CODLOTE," + "C.CODEMPTM, C.CODFILIALTM, C.CODTIPOMOV," + "C.CODEMP, C.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "C.CODCOMPRA CODMASTER, IC.CODITCOMPRA CODITEM," + "IC.CODEMPNT, IC.CODFILIALNT, IC.CODNAT, " + "C.DTENTCOMPRA DTPROC, C.DOCCOMPRA DOCPROC, C.FLAG," + "IC.QTDITCOMPRA QTDPROC, IC.CUSTOITCOMPRA CUSTOPROC, " + "IC.CODEMPAX, IC.CODFILIALAX, IC.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM CPCOMPRA C,CPITCOMPRA IC " + "WHERE IC.CODCOMPRA=C.CODCOMPRA AND " + "IC.CODEMP=C.CODEMP AND IC.CODFILIAL=C.CODFILIAL AND IC.QTDITCOMPRA > 0 AND " + "C.CODEMP=? AND IC.CODPROD = ?" + sWhereCompra; sSQLOP = "SELECT 'O' TIPOPROC, O.CODEMPPD, O.CODFILIALPD, O.CODPROD," + "O.CODEMPLE, O.CODFILIALLE, O.CODLOTE," + "O.CODEMPTM, O.CODFILIALTM, O.CODTIPOMOV," + "O.CODEMP, O.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA ," + "O.CODOP CODMASTER, CAST(O.SEQOP AS INTEGER) CODITEM," + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "coalesce(oe.dtent,O.DTFABROP) DTPROC, " + "O.CODOP DOCPROC, 'N' FLAG, " + "coalesce(oe.qtdent,O.QTDFINALPRODOP) QTDPROC, " + "( SELECT SUM(PD.CUSTOMPMPROD) FROM PPITOP IT, EQPRODUTO PD " + "WHERE IT.CODEMP=O.CODEMP AND IT.CODFILIAL=O.CODFILIAL AND " + "IT.CODOP=O.CODOP AND IT.SEQOP=O.SEQOP AND " + "PD.CODEMP=IT.CODEMPPD AND PD.CODFILIAL=IT.CODFILIALPD AND " + "PD.CODPROD=IT.CODPROD) CUSTOPROC, " + "O.CODEMPAX, O.CODFILIALAX, O.CODALMOX, oe.seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM PPOP O " + " left outer join ppopentrada oe on oe.codemp=o.codemp and oe.codfilial=o.codfilial and oe.codop=o.codop and oe.seqop=o.seqop " + "WHERE O.QTDFINALPRODOP > 0 AND " + "O.CODEMP=? AND O.CODPROD = ? " + sWhereOP; sSQLOP_SP = "SELECT 'S' TIPOPROC, O.CODEMPPD, O.CODFILIALPD, O.CODPROD," + "O.CODEMPLE, O.CODFILIALLE, O.CODLOTE," + "O.CODEMPTM, O.CODFILIALTM, O.CODTIPOMOV," + "O.CODEMP, O.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA ," + "O.CODOP CODMASTER, CAST(O.SEQOP AS INTEGER) CODITEM," + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "coalesce(o.dtsubprod,Op.DTFABROP) DTPROC, " + "O.CODOP DOCPROC, 'N' FLAG, " + "O.QTDITSP QTDPROC, " + "( SELECT PD.CUSTOMPMPROD FROM EQPRODUTO PD " + "WHERE PD.CODEMP=O.CODEMPPD AND PD.CODFILIAL=O.CODFILIALPD AND " + "PD.CODPROD=O.CODPROD) CUSTOPROC, " + "OP.CODEMPAX, OP.CODFILIALAX, OP.CODALMOX, CAST(NULL AS SMALLINT) as seqent, O.SEQSUBPROD " + "FROM PPOPSUBPROD O, PPOP OP " + "WHERE O.QTDITSP > 0 AND " + "O.CODEMP=OP.CODEMP and O.CODFILIAL=OP.CODFILIAL and O.CODOP=OP.CODOP and O.SEQOP=OP.SEQOP AND " + "O.CODEMP=? AND O.CODPROD = ?" + sWhereOP_SP; sSQLRMA = "SELECT 'R' TIPOPROC, IT.CODEMPPD, IT.CODFILIALPD, IT.CODPROD, " + "IT.CODEMPLE, IT.CODFILIALLE, IT.CODLOTE, " + "RMA.CODEMPTM, RMA.CODFILIALTM, RMA.CODTIPOMOV, " + "RMA.CODEMP, RMA.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "IT.CODRMA CODMASTER, CAST(IT.CODITRMA AS INTEGER) CODITEM, " + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "COALESCE(IT.DTAEXPITRMA,RMA.DTAREQRMA) DTPROC, " + "RMA.CODRMA DOCPROC, 'N' FLAG, " + "IT.QTDEXPITRMA QTDPROC, IT.PRECOITRMA CUSTOPROC," + "IT.CODEMPAX, IT.CODFILIALAX, IT.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM EQRMA RMA ,EQITRMA IT " + "WHERE IT.CODRMA=RMA.CODRMA AND " + "IT.CODEMP=RMA.CODEMP AND IT.CODFILIAL=RMA.CODFILIAL AND " + "IT.QTDITRMA > 0 AND " + "RMA.CODEMP=? AND IT.CODPROD = ?" + sWhereRMA; sSQLVenda = "SELECT 'V' TIPOPROC, IV.CODEMPPD, IV.CODFILIALPD, IV.CODPROD," + "IV.CODEMPLE, IV.CODFILIALLE, IV.CODLOTE," + "V.CODEMPTM, V.CODFILIALTM, V.CODTIPOMOV," + "V.CODEMP, V.CODFILIAL, V.TIPOVENDA, " + "V.CODVENDA CODMASTER, IV.CODITVENDA CODITEM, " + "IV.CODEMPNT, IV.CODFILIALNT, IV.CODNAT, " + "V.DTEMITVENDA DTPROC, V.DOCVENDA DOCPROC, V.FLAG, " + "IV.QTDITVENDA QTDPROC, IV.VLRLIQITVENDA CUSTOPROC, " + "IV.CODEMPAX, IV.CODFILIALAX, IV.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM VDVENDA V ,VDITVENDA IV " + "WHERE IV.CODVENDA=V.CODVENDA AND IV.TIPOVENDA = V.TIPOVENDA AND " + "IV.CODEMP=V.CODEMP AND IV.CODFILIAL=V.CODFILIAL AND " + "IV.QTDITVENDA > 0 AND " + "V.CODEMP=? AND IV.CODPROD = ?" + sWhereVenda; try { state(sProd + "Iniciando reconstru��o..."); sSQL = sSQLInventario + " UNION ALL " + sSQLCompra + " UNION ALL " + sSQLOP + " UNION ALL " + sSQLOP_SP + " UNION ALL " + sSQLRMA + " UNION ALL " + sSQLVenda + " ORDER BY 19,1,20"; System.out.println(sSQL); ps = con.prepareStatement(sSQL); ps.setInt(paramCons.CODEMPIV.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODIV.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPCP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODCP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPOP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODOP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPOPSP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODOPSP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPRM.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODRM.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPVD.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODVD.ordinal(), iCodProd); rs = ps.executeQuery(); bOK = true; while (rs.next() && bOK) { bOK = insereMov(rs, sProd); } rs.close(); ps.close(); state(sProd + "Aguardando grava��o final..."); } catch (SQLException err) { bOK = false; err.printStackTrace(); Funcoes.mensagemErro(null, "Erro ao reconstruir base!\n" + err.getMessage(), true, con, err); } } try { if (bOK) { con.commit(); state(sProd + "Registros processados com sucesso!"); } else { state(sProd + "Registros antigos restaurados!"); con.rollback(); } } catch (SQLException err) { err.printStackTrace(); Funcoes.mensagemErro(null, "Erro ao relizar procedimento!\n" + err.getMessage(), true, con, err); } } finally { sSQL = null; sSQLCompra = null; sSQLInventario = null; sSQLVenda = null; sSQLRMA = null; sWhere = null; sProd = null; sWhereCompra = null; sWhereInventario = null; sWhereVenda = null; sWhereRMA = null; rs = null; ps = null; bRunProcesso = false; btProcessar.setEnabled(true); } return bOK; }
Code Sample 2:
public int subclass(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "isa", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
|
11
|
Code Sample 1:
@SuppressWarnings("unchecked") protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException { Enumeration<String> attrNameEnum = request.getSession().getAttributeNames(); String attrName; while (attrNameEnum.hasMoreElements()) { attrName = attrNameEnum.nextElement(); if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) { variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName)); } } variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI()); Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { temp.process(variableMap, new OutputStreamWriter(outStream)); response.setContentLength(outStream.size()); IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new Admin4jRuntimeException(e); } }
Code Sample 2:
public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } }
|
00
|
Code Sample 1:
public static String encryptPass(String pass) { String passEncrypt; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } md5.update(pass.getBytes()); BigInteger dis = new BigInteger(1, md5.digest()); passEncrypt = dis.toString(16); return passEncrypt; }
Code Sample 2:
protected void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
11
|
Code Sample 1:
@Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
Code Sample 2:
private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
|
11
|
Code Sample 1:
public static void copyFile(File srcFile, File dstFile) { logger.info("Create file : " + dstFile.getPath()); try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel dstChannel = new FileOutputStream(dstFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
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(); } } }
|
00
|
Code Sample 1:
private void _connect() throws SocketException, IOException { try { ftpClient.disconnect(); } catch (Exception ex) { } ftpClient.connect(host, port); ftpClient.login("anonymous", ""); ftpClient.enterLocalActiveMode(); }
Code Sample 2:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = null; ServletOutputStream outstream = null; try { String action = req.getParameter("nmrshiftdbaction"); String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF"); TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties")); tc.init(); int spectrumId = -1; DBSpectrum spectrum = null; Export export = null; String format = req.getParameter("format"); if (action.equals("test")) { try { res.setContentType("text/plain"); out = res.getWriter(); List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1"); if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt(); out.write("success"); } catch (Exception ex) { out.write("failure"); } } else if (action.equals("rss")) { int numbertoexport = 10; out = res.getWriter(); if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } res.setContentType("text/xml"); RssWriter rssWriter = new RssWriter(); rssWriter.setWriter(res.getWriter()); AtomContainerSet soac = new AtomContainerSet(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;"; List l = NmrshiftdbUserPeer.executeQuery(query); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1); soac.addAtomContainer(cdkmol); rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req)); rssWriter.getDatemap().put(cdkmol, mol.getDate()); rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback()); rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName()); rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig())); Vector v = mol.getDBCanonicalNames(); for (int k = 0; k < v.size(); k++) { DBCanonicalName canonName = (DBCanonicalName) v.get(k); if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") { rssWriter.getInchimap().put(cdkmol, canonName.getName()); break; } } rssWriter.setTitle("NMRShiftDB"); rssWriter.setLink("http://www.nmrshiftdb.org"); rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data"); rssWriter.setPublisher("NMRShiftDB.org"); rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif"); rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss"); Collection coll = new ArrayList(); Vector spectra = mol.selectSpectra(null); for (int k = 0; k < spectra.size(); k++) { Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Element el2 = el.getChildElements().get(0); el.removeChild(el2); coll.add(el2); } rssWriter.getMultiMap().put(cdkmol, coll); } rssWriter.write(soac); } else if (action.equals("getattachment")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid"))); outstream.write(sample.getAttachment()); } else if (action.equals("createreport")) { res.setContentType("application/pdf"); outstream = res.getOutputStream(); boolean yearly = req.getParameter("style").equals("yearly"); int yearstart = Integer.parseInt(req.getParameter("yearstart")); int yearend = Integer.parseInt(req.getParameter("yearend")); int monthstart = 0; int monthend = 0; if (!yearly) { monthstart = Integer.parseInt(req.getParameter("monthstart")); monthend = Integer.parseInt(req.getParameter("monthend")); } int type = Integer.parseInt(req.getParameter("type")); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper"); Map parameters = new HashMap(); if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend); DBConnection dbconn = TurbineDB.getConnection(); Connection conn = dbconn.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; if (type == 1) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME"); } else if (type == 2) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME"); } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs)); JasperExportManager.exportReportToPdfStream(jasperPrint, outstream); dbconn.close(); } else if (action.equals("exportcmlbyinchi")) { res.setContentType("text/xml"); out = res.getWriter(); String inchi = req.getParameter("inchi"); String spectrumtype = req.getParameter("spectrumtype"); Criteria crit = new Criteria(); crit.add(DBCanonicalNamePeer.NAME, inchi); crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID); crit.add(DBSpectrumTypePeer.NAME, spectrumtype); try { GeneralUtils.logToSql(crit.toString(), null); } catch (Exception ex) { } Vector spectra = DBSpectrumPeer.doSelect(crit); if (spectra.size() == 0) { out.write("No such molecule or spectrum"); } else { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); for (int k = 0; k < spectra.size(); k++) { Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); } out.write(cmlElement.toXML()); } } else if (action.equals("namelist")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); Criteria crit = new Criteria(); crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.add(DBSpectrumPeer.REVIEW_FLAG, "true"); Vector v = DBMoleculePeer.doSelect(crit); for (int i = 0; i < v.size(); i++) { if (i % 500 == 0) { if (i != 0) { zipout.write(new String("<p>The list is continued <a href=\"nmrshiftdb.names." + i + ".html\">here</a></p></body></html>").getBytes()); zipout.closeEntry(); } zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html")); zipout.write(new String("<html><body><h1>This is a list of strcutures in <a href=\"http://www.nmrshiftdb.org\">NMRShiftDB</a>, starting at " + i + ", Its main purpose is to be found by search engines</h1>").getBytes()); } DBMolecule mol = (DBMolecule) v.get(i); zipout.write(new String("<p><a href=\"" + mol.getEasylink(req) + "\">").getBytes()); Vector cannames = mol.getDBCanonicalNames(); for (int k = 0; k < cannames.size(); k++) { zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes()); } Vector chemnames = mol.getDBChemicalNames(); for (int k = 0; k < chemnames.size(); k++) { zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes()); } zipout.write(new String("</a>. Information we have got: NMR spectra").getBytes()); Vector spectra = mol.selectSpectra(); for (int k = 0; k < spectra.size(); k++) { zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes()); } if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes()); zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes()); zipout.write(new String("</p>").getBytes()); } zipout.write(new String("</body></html>").getBytes()); zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("predictor")) { if (req.getParameter("symbol") == null) { res.setContentType("text/plain"); out = res.getWriter(); out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C"); } res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); String filename = "org/openscience/nmrshiftdb/PredictionTool.class"; zipout.putNextEntry(new ZipEntry(filename)); JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar"))); JarEntry entry = jip.getNextJarEntry(); while (entry.getName().indexOf("PredictionTool.class") == -1) { entry = jip.getNextJarEntry(); } for (int i = 0; i < entry.getSize(); i++) { zipout.write(jip.read()); } zipout.closeEntry(); zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv")); int i = 0; org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection(); HashMap mapsmap = new HashMap(); while (true) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000"); int m = 0; while (rs.next()) { String code = rs.getString(1); Double value = new Double(rs.getString(2)); String symbol = rs.getString(3); if (mapsmap.get(symbol) == null) { mapsmap.put(symbol, new HashMap()); } for (int spheres = 6; spheres > 0; spheres--) { StringBuffer hoseCodeBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(code, "()/"); for (int k = 0; k < spheres; k++) { if (st.hasMoreTokens()) { String partcode = st.nextToken(); hoseCodeBuffer.append(partcode); } if (k == 0) { hoseCodeBuffer.append("("); } else if (k == 3) { hoseCodeBuffer.append(")"); } else { hoseCodeBuffer.append("/"); } } String hoseCode = hoseCodeBuffer.toString(); if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) { ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList()); } ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value); } m++; } i++; stmt.close(); if (m == 0) break; } Set keySet = mapsmap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String symbol = (String) it.next(); HashMap hosemap = ((HashMap) mapsmap.get(symbol)); Set keySet2 = hosemap.keySet(); Iterator it2 = keySet2.iterator(); while (it2.hasNext()) { String hoseCode = (String) it2.next(); ArrayList list = ((ArrayList) hosemap.get(hoseCode)); double[] values = new double[list.size()]; for (int k = 0; k < list.size(); k++) { values[k] = ((Double) list.get(k)).doubleValue(); } zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes()); } } zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; i = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("exportspec") || action.equals("exportmol")) { if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid"))); export = new Export(spectrum); } else if (action.equals("exportmdl")) { res.setContentType("text/plain"); outstream = res.getOutputStream(); DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid"))); outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes()); } else if (action.equals("exportlastinputs")) { format = action; } else if (action.equals("printpredict")) { res.setContentType("text/html"); out = res.getWriter(); HttpSession session = req.getSession(); VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true); StringWriter w = new StringWriter(); Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w); out.println(w.toString()); } else { res.setContentType("text/html"); out = res.getWriter(); out.println("No valid action"); } if (format == null) format = ""; if (format.equals("pdf") || format.equals("rtf")) { res.setContentType("application/" + format); out = res.getWriter(); } if (format.equals("docbook")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); } if (format.equals("svg")) { res.setContentType("image/x-svg"); out = res.getWriter(); } if (format.equals("tiff")) { res.setContentType("image/tiff"); outstream = res.getOutputStream(); } if (format.equals("jpeg")) { res.setContentType("image/jpeg"); outstream = res.getOutputStream(); } if (format.equals("png")) { res.setContentType("image/png"); outstream = res.getOutputStream(); } if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) { res.setContentType("text/plain"); out = res.getWriter(); } if (format.equals("simplehtml") || format.equals("exportlastinputs")) { res.setContentType("text/html"); out = res.getWriter(); } if (action.equals("exportlastinputs")) { int numbertoexport = 4; if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } NmrshiftdbUser user = null; try { user = NmrshiftdbUserPeer.getByName(req.getParameter("username")); } catch (NmrshiftdbException ex) { out.println("Seems <code>username</code> is not OK: " + ex.getMessage()); } if (user != null) { List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER where LOGIN_NAME=\"" + user.getUserName() + "\";"); Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate(); if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) { out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!"); } else { NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";"); Vector<String> parameters = new Vector<String>(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;"; l = NmrshiftdbUserPeer.executeQuery(query); String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString(); url = url.substring(0, url.length() - 17); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); parameters.add(new String("<a href=\"" + url + "/portal/pane0/Results?nmrshiftdbaction=showDetailsFromHome&molNumber=" + mol.getMoleculeId() + "\"><img src=\"" + javax.servlet.http.HttpUtils.getRequestURL(req).toString() + "?nmrshiftdbaction=exportmol&spectrumid=" + ((DBSpectrum) mol.getDBSpectrums().get(0)).getSpectrumId() + "&format=jpeg&size=150x150&backcolor=12632256\"></a>")); } VelocityContext context = new VelocityContext(); context.put("results", parameters); StringWriter w = new StringWriter(); Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w); out.println(w.toString()); } } } if (action.equals("exportspec")) { if (format.equals("txt")) { String lastsearchtype = req.getParameter("lastsearchtype"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues")); spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)); } Vector v = spectrum.getOptions(); DBMolecule mol = spectrum.getDBMolecule(); out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r"); out.print("\n\rAtom\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t"); out.print("Meas."); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tInput\tDiff"); } out.print("\n\r"); out.print("No.\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t"); out.print("Shift"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tShift\tM-I"); } out.print("\n\r"); for (int i = 0; i < v.size(); i++) { out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange()); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta()); } out.print("\n\r"); } } if (format.equals("simplehtml")) { String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[0] = new File(i1).getName(); String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[1] = new File(i2).getName(); String docbook = export.getHtml(); out.print(docbook); } if (format.equals("pdf") || format.equals("rtf")) { String svgSpec = export.getSpecSvg(400, 200); String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg"; new FileOutputStream(svgspecfile).write(svgSpec.getBytes()); export.pictures[1] = svgspecfile; String molSvg = export.getMolSvg(true); String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg"; new FileOutputStream(svgmolfile).write(molSvg.getBytes()); export.pictures[0] = svgmolfile; String docbook = export.getDocbook("pdf", "SVG"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos)); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out2 = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2); TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); Source src = new StreamSource(new StringReader(baos.toString())); Result res2 = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res2); out.print(out2.toString()); } if (format.equals("docbook")) { String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes()); export.pictures[0] = new File(i1).getName(); String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i2).write(export.getMolSvg(true).getBytes()); export.pictures[1] = new File(i2).getName(); String docbook = export.getDocbook("pdf", "SVG"); String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml"; new FileOutputStream(docbookfile).write(docbook.getBytes()); ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 }); outstream.write(baos.toByteArray()); } if (format.equals("svg")) { out.print(export.getSpecSvg(400, 200)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("cml")) { out.print(spectrum.getCmlSpect().toXML()); } if (format.equals("cmlboth")) { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H")); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); Element parentspec = spectrum.getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); out.write(cmlElement.toXML()); } if (format.indexOf("exsection") == 0) { StringTokenizer st = new StringTokenizer(format, "-"); st.nextToken(); String template = st.nextToken(); Criteria crit = new Criteria(); crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId()); Vector v = spectrum.getDBMolecule().getDBSpectrums(crit); VelocityContext context = new VelocityContext(); context.put("spectra", v); context.put("molecule", spectrum.getDBMolecule()); StringWriter w = new StringWriter(); Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w); out.write(w.toString()); } } if (action.equals("exportmol")) { int width = -1; int height = -1; if (req.getParameter("size") != null) { StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x"); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } boolean shownumbers = true; if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) { shownumbers = false; } if (req.getParameter("backcolor") != null) { export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor"))); } if (req.getParameter("markatom") != null) { export.selected = Integer.parseInt(req.getParameter("markatom")) - 1; } if (format.equals("svg")) { out.print(export.getMolSvg(true)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("mdl")) { out.println(spectrum.getDBMolecule().getStructureFile(1, false)); } if (format.equals("cml")) { out.println(spectrum.getDBMolecule().getCMLString(1)); } } if (out != null) out.flush(); else outstream.flush(); } catch (Exception ex) { ex.printStackTrace(); out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true)); out.flush(); } }
|
11
|
Code Sample 1:
public static String[] parseM3U(String strURL, Context c) { URL url; URLConnection urlConn = null; String TAG = "parseM3U"; Vector<String> radio = new Vector<String>(); final String filetoken = "http"; try { url = new URL(strURL); urlConn = url.openConnection(); Log.d(TAG, "Got data"); } catch (IOException ioe) { Log.e(TAG, "Could not connect to " + strURL); } try { DataInputStream in = new DataInputStream(urlConn.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String temp = strLine.toLowerCase(); Log.d(TAG, strLine); if (temp.startsWith(filetoken)) { radio.add(temp); Log.d(TAG, "Found audio " + temp); } } br.close(); in.close(); } catch (Exception e) { Log.e(TAG, "Trouble reading file: " + e.getMessage()); } String[] t = new String[0]; String[] r = null; if (radio.size() != 0) { r = (String[]) radio.toArray(t); Log.d(TAG, "Found total: " + String.valueOf(r.length)); } return r; }
Code Sample 2:
public String postXmlRequest(String url, String data) { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); StringBuffer responseStr = new StringBuffer(); try { System.out.println(data); Log4j.logger.info("Request:\n" + data); StringEntity reqEntity = new StringEntity(data, "UTF-8"); reqEntity.setContentType("text/xml"); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); this.setPostSatus(response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { responseStr.append(line + "\n"); } if (entity != null) { entity.consumeContent(); } } catch (Exception ex) { ex.printStackTrace(); } System.out.println(responseStr); Log4j.logger.info("Response:\n" + responseStr); return responseStr.toString(); }
|
11
|
Code Sample 1:
@org.junit.Test public void simpleRead() throws Exception { final InputStream istream = StatsInputStreamTest.class.getResourceAsStream("/testFile.txt"); final StatsInputStream ris = new StatsInputStream(istream); assertEquals("read size", 0, ris.getSize()); IOUtils.copy(ris, new NullOutputStream()); assertEquals("in the end", 30, ris.getSize()); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public boolean connect() { if (connectStatus > -1) return (connectStatus == 1); connectStatus = 0; try { URL url = new URL(getURL()); m_connection = (HttpURLConnection) url.openConnection(); m_connection.connect(); processHeaders(); m_inputStream = m_connection.getInputStream(); } catch (MalformedURLException e) { newError("connect failed", e, true); } catch (IOException e) { newError("connect failed", e, true); } return (connectStatus == 1); }
Code Sample 2:
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
|
00
|
Code Sample 1:
@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; }
Code Sample 2:
@Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
|
00
|
Code Sample 1:
public static String md5(String s) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); String output = bigInt.toString(16); return prepad(output, 32, '0'); } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm. we are sunk."); return s; } }
Code Sample 2:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente = '" + id + "'"; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
|
11
|
Code Sample 1:
public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
Code Sample 2:
public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("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 bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
public ProductListByCatHandler(int cathegory, int langId) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Catalog.groovy?method=GetProductListByCategory&category_id=" + cathegory + "&language_id=" + langId); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("product"); for (int i = 0; i < nl.getLength(); i++) { Element nodes = (Element) nl.item(i); String id = nodes.getAttribute("id").toString(); NodeList name = nodes.getElementsByTagName("name"); NodeList rank2 = nodes.getElementsByTagName("sales_rank"); NodeList price = nodes.getElementsByTagName("price"); NodeList url2 = nodes.getElementsByTagName("image_url"); String nameS = getCharacterDataFromElement((Element) name.item(0)); String rank2S = getCharacterDataFromElement((Element) rank2.item(0)); String priceS = getCharacterDataFromElement((Element) price.item(0)); String url2S = getCharacterDataFromElement((Element) url2.item(0)); list.add(new ProductShort(id, nameS, rank2S, priceS, url2S)); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
protected void setOuterIP() { try { URL url = new URL("http://elm-ve.sf.net/ipCheck/ipCheck.cgi"); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ip = br.readLine(); ip = ip.trim(); bridgeOutIPTF.setText(ip); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static int proxy(java.net.URI uri, HttpServletRequest req, HttpServletResponse res) throws IOException { final HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(uri.getHost()); HttpMethodBase httpMethod = null; if (HttpRpcServer.METHOD_GET.equalsIgnoreCase(req.getMethod())) { httpMethod = new GetMethod(uri.toString()); httpMethod.setFollowRedirects(true); } else if (HttpRpcServer.METHOD_POST.equalsIgnoreCase(req.getMethod())) { httpMethod = new PostMethod(uri.toString()); final Enumeration parameterNames = req.getParameterNames(); if (parameterNames != null) while (parameterNames.hasMoreElements()) { final String parameterName = (String) parameterNames.nextElement(); for (String parameterValue : req.getParameterValues(parameterName)) ((PostMethod) httpMethod).addParameter(parameterName, parameterValue); } ((PostMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream())); } if (httpMethod == null) throw new IllegalArgumentException("Unsupported http request method"); final int responseCode; final Enumeration headers = req.getHeaderNames(); if (headers != null) while (headers.hasMoreElements()) { final String headerName = (String) headers.nextElement(); final Enumeration headerValues = req.getHeaders(headerName); while (headerValues.hasMoreElements()) { httpMethod.setRequestHeader(headerName, (String) headerValues.nextElement()); } } final HttpState httpState = new HttpState(); if (req.getCookies() != null) for (Cookie cookie : req.getCookies()) { String host = req.getHeader("Host"); if (StringUtils.isEmpty(cookie.getDomain())) cookie.setDomain(StringUtils.isEmpty(host) ? req.getServerName() + ":" + req.getServerPort() : host); if (StringUtils.isEmpty(cookie.getPath())) cookie.setPath("/"); httpState.addCookie(new org.apache.commons.httpclient.Cookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure())); } httpMethod.setQueryString(req.getQueryString()); responseCode = (new HttpClient()).executeMethod(hostConfig, httpMethod, httpState); if (responseCode < 0) { httpMethod.releaseConnection(); return responseCode; } if (httpMethod.getResponseHeaders() != null) for (Header header : httpMethod.getResponseHeaders()) res.setHeader(header.getName(), header.getValue()); final InputStream in = httpMethod.getResponseBodyAsStream(); final OutputStream out = res.getOutputStream(); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); httpMethod.releaseConnection(); return responseCode; }
Code Sample 2:
public final void saveAsCopy(String current_image, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; String source = temp_dir + key + current_image; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
|
00
|
Code Sample 1:
public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
Code Sample 2:
private String calculateCredential(Account account) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } try { md5.update(account.getUsername().getBytes("UTF-8")); md5.update(account.getCryptPassword().getBytes("UTF-8")); md5.update(String.valueOf(account.getObjectId()).getBytes("UTF-8")); md5.update(account.getUid().getBytes("UTF-8")); byte[] digest = md5.digest(); return TextUtils.calculateMD5(digest); } catch (UnsupportedEncodingException e) { return null; } }
|
11
|
Code Sample 1:
@Override public void run() { log.debug("Now running...."); log.debug("Current env. variables:"); try { this.infoNotifiers("Environment parameters after modifications:"); this.logEnvironment(); this.infoNotifiers("Dump thread will now run..."); this.endNotifiers(); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } List<String> cmd = new LinkedList<String>(); cmd.add("gzip"); cmd.add(info.getDumpFileName()); File basePath = this.pb.directory(); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } info.setDumpFileName(info.getDumpFileName() + ".gz"); info.setMD5SumFileName(info.getDumpFileName() + ".md5sum"); cmd = new LinkedList<String>(); cmd.add("md5sum"); cmd.add("-b"); cmd.add(info.getDumpFileName()); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); this.process = this.pb.start(); BufferedOutputStream md5sumFileOut = new BufferedOutputStream(new FileOutputStream(basePath.getAbsolutePath() + File.separatorChar + info.getMD5SumFileName())); IOUtils.copy(this.process.getInputStream(), md5sumFileOut); this.process.waitFor(); md5sumFileOut.flush(); md5sumFileOut.close(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip MD5Sum Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } else { this.startNotifiers(); this.infoNotifiers("Dump, gzip and md5sum sucessfuly completed."); this.endNotifiers(); } } catch (IOException e) { String message = "IOException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (InterruptedException e) { String message = "InterruptedException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (IntegrationException e) { String message = "IntegrationException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } }
Code Sample 2:
public static void copy(final File source, final File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); dest.setLastModified(source.lastModified()); } finally { close(in); close(out); } }
|
00
|
Code Sample 1:
public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
@SuppressWarnings("unchecked") public static <T extends Class> Collection<T> listServices(T serviceType, ClassLoader classLoader) throws IOException, ClassNotFoundException { final Collection<T> result = new LinkedHashSet<T>(); final Enumeration<URL> resouces = classLoader.getResources("META-INF/services/" + serviceType.getName()); while (resouces.hasMoreElements()) { final URL url = resouces.nextElement(); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String line = reader.readLine(); while (line != null) { if (line.startsWith("#")) { } else if ("".equals(line.trim())) { } else { final T implClass = (T) Class.forName(line, true, classLoader); if (!serviceType.isAssignableFrom(implClass)) { throw new IllegalStateException(String.format("%s: class %s does not implement required interfafce %s", url, implClass, serviceType)); } result.add(implClass); } line = reader.readLine(); } } finally { reader.close(); } } return result; }
|
11
|
Code Sample 1:
public static boolean joinFiles(File dest, Collection<File> sources) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fos = new FileOutputStream(dest); for (File source : sources) { fis = new FileInputStream(source); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; } fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("error joining files to " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
Code Sample 2:
public void xtestFile2() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile2.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
|
00
|
Code Sample 1:
public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); }
Code Sample 2:
public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
|
00
|
Code Sample 1:
protected InputStream makeSignedRequestAndGetJSONData(String url) { try { if (consumer == null) loginOAuth(); } catch (Exception e) { consumer = null; e.printStackTrace(); } DefaultHttpClient httpClient = new DefaultHttpClient(); URI uri; InputStream data = null; try { uri = new URI(url); HttpGet method = new HttpGet(uri); consumer.sign(method); HttpResponse response = httpClient.execute(method); data = response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); } return data; }
Code Sample 2:
public boolean download(URL url, File file) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[4096]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } } catch (Exception e) { System.out.println(e); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { return false; } } return true; }
|
00
|
Code Sample 1:
protected boolean hasOsmTileETag(String eTag) throws IOException { URL url; url = new URL(tile.getUrl()); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); prepareHttpUrlConnection(urlConn); urlConn.setRequestMethod("HEAD"); urlConn.setReadTimeout(30000); String osmETag = urlConn.getHeaderField("ETag"); if (osmETag == null) return true; return (osmETag.equals(eTag)); }
Code Sample 2:
public static File gzipLog() throws IOException { RunnerClass.nfh.flush(); File log = new File(RunnerClass.homedir + "pj.log"); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File(log.getCanonicalPath() + ".pjl"))); FileInputStream in = new FileInputStream(log); int bufferSize = 4 * 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); return new File(log.getCanonicalPath() + ".pjl"); }
|
00
|
Code Sample 1:
public static String encryptPassword(String originalPassword) { if (!StringUtils.hasText(originalPassword)) { originalPassword = randomPassword(); } try { MessageDigest md5 = MessageDigest.getInstance(PASSWORD_ENCRYPTION_TYPE); md5.update(originalPassword.getBytes()); byte[] bytes = md5.digest(); int value; StringBuilder buf = new StringBuilder(); for (byte aByte : bytes) { value = aByte; if (value < 0) { value += 256; } if (value < 16) { buf.append("0"); } buf.append(Integer.toHexString(value)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { log.debug("Do not encrypt password,use original password", e); return originalPassword; } }
Code Sample 2:
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"); } }
|
00
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public void run() throws Exception { Properties buildprops = new Properties(); try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("build.properties"); InputStream is = url.openStream(); ; buildprops.load(is); } catch (Exception ex) { log.error("Problem getting build props", ex); } System.out.println("Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown")); validate(); if (log.isInfoEnabled()) { log.info("Starting Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown")); } MainConfig config = MainConfig.newInstance(); basedir = config.getBaseDirectory(); if (log.isInfoEnabled()) { log.info("basedir = " + basedir); } SchedulerFactory schedFact = new StdSchedulerFactory(); sched = schedFact.getScheduler(); NodeList reports = config.getReports(); for (int x = 0; x < reports.getLength(); x++) { try { if (log.isInfoEnabled()) { log.info("Adding report at index " + x); } Node report = reports.item(x); runReport(report); } catch (Exception ex) { if (log.isErrorEnabled()) { log.error("Can't add a report at report index " + x, ex); } } } addStatsJob(); sched.start(); WebServer webserver = new WebServer(8080); webserver.setParanoid(false); webserver.start(); }
|
11
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentType = req.getParameter("type"); String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing File Arg"); return; } File f = new File(arg); if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } if (contentType != null) { resp.setContentType(contentType); } log.debug("Requested File: " + f + " as type: " + contentType); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
Code Sample 2:
public void Copy() throws IOException { if (!FileDestination.exists()) { FileDestination.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(FileSource).getChannel(); destination = new FileOutputStream(FileDestination).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
private static long copy(InputStream source, OutputStream sink) { try { return IOUtils.copyLarge(source, sink); } catch (IOException e) { throw new FaultException("System error copying stream", e); } finally { IOUtils.closeQuietly(source); IOUtils.closeQuietly(sink); } }
Code Sample 2:
private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); data = Data.valueOf(md.digest()); try { response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); setID(response.getWord()); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } }
|
11
|
Code Sample 1:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } }
Code Sample 2:
public Reader transform(Reader reader, Map<String, Object> parameterMap) { try { File file = File.createTempFile("srx2", ".srx"); file.deleteOnExit(); Writer writer = getWriter(getFileOutputStream(file.getAbsolutePath())); transform(reader, writer, parameterMap); writer.close(); Reader resultReader = getReader(getFileInputStream(file.getAbsolutePath())); return resultReader; } catch (IOException e) { throw new IORuntimeException(e); } }
|
00
|
Code Sample 1:
private static void findDictionary() { java.net.URL url = Translator.class.getResource("Translator.class"); String location = url.getFile(); String dictionaryName = (String) Settings.getDefault().getSetting("dictionary"); InputStream inputStream; try { if (location.indexOf(".jar!") == -1) inputStream = new FileInputStream(location.substring(0, location.indexOf("Translator.class")) + dictionaryName); else { JarFile jarFile; if (location.indexOf("rachota.sourceforge.net") != -1) { String fileName = location.substring(0, location.indexOf("!/") + 2); url = new URL("jar:http://rachota.sourceforge.net/rachota_22.jar!/"); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarFile = jarConnection.getJarFile(); } else { String fileName = System.getProperty("os.name").indexOf("Windows") == -1 ? "/" : ""; fileName = fileName + location.substring(6, location.indexOf(".jar") + 4); fileName = Tools.replaceAll(fileName, "%20", " "); jarFile = new JarFile(fileName); } ZipEntry entry = jarFile.getEntry("org/cesilko/rachota/core/" + dictionaryName); if (entry == null) { entry = jarFile.getEntry("org/cesilko/rachota/core/Dictionary_en_US.properties"); Settings.getDefault().setSetting("dictionary", "Dictionary_en_US.properties"); } inputStream = jarFile.getInputStream(entry); } dictionary = new PropertyResourceBundle(inputStream); } catch (Exception e) { System.out.println("Error: Reading from " + dictionaryName + " dictionary failed."); e.printStackTrace(); } }
Code Sample 2:
public static void compressAll(File dir, File file) throws IOException { if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.setLevel(0); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytesRead; for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); }
|
00
|
Code Sample 1:
public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); }
Code Sample 2:
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(); }
|
00
|
Code Sample 1:
public static InputSource openInputSource(String resource) { InputSource src = null; URL url = findResource(resource); if (url != null) { try { InputStream in = url.openStream(); src = new InputSource(in); src.setSystemId(url.toExternalForm()); } catch (IOException e) { } } return src; }
Code Sample 2:
private void analyseCorpus(final IStatusDisplayer fStatus) { final String sDistrosFile = "Distros.tmp"; final String sSymbolsFile = "Symbols.tmp"; Chunker = new EntropyChunker(); int Levels = 2; sgOverallGraph = new SymbolicGraph(1, Levels); siIndex = new SemanticIndex(sgOverallGraph); try { siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor(); } catch (IOException ioe) { siIndex.MeaningExtractor = null; } try { DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0); dsSet.createSets(true, (double) 100 / 100); int iCurCnt, iTotal; String sFile = ""; Iterator iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } appendToLog("Training chunker..."); Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET)); appendToLog("Setting delimiters..."); setDelimiters(Chunker.getDelimiters()); iCurCnt = 0; cdDoc = new DistributionDocument[Levels]; for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt); fStatus.setVisible(true); ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1); appendToLog("(Pass 1/3) Loading files..." + sFile); TreeSet tsOverallSymbols = new TreeSet(); while (iIter.hasNext()) { sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal); final DistributionDocument[] cdDocArg = cdDoc; final String sFileArg = sFile; for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) { final int iCntArg = iCnt; while (!t.addThreadFor(new Runnable() { public void run() { if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else { cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false); } } })) Thread.yield(); } try { t.waitUntilCompletion(); } catch (InterruptedException ex) { ex.printStackTrace(System.err); appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString()); sgOverallGraph.loadFromFile(sFile); fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal); Thread.yield(); } Set sSymbols = null; File fPreviousSymbols = new File(sSymbolsFile); boolean bSymbolsLoadedOK = false; if (fPreviousSymbols.exists()) { System.err.println("ATTENTION: Using previous symbols..."); try { FileInputStream fis = new FileInputStream(fPreviousSymbols); ObjectInputStream ois = new ObjectInputStream(fis); sSymbols = (Set) ois.readObject(); ois.close(); bSymbolsLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); } } if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus); int iMinSymbolSize = Integer.MAX_VALUE; int iMaxSymbolSize = Integer.MIN_VALUE; Iterator iSymbol = sSymbols.iterator(); while (iSymbol.hasNext()) { String sCurSymbol = (String) iSymbol.next(); if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length(); if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length(); } try { FileOutputStream fos = new FileOutputStream(sSymbolsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(sSymbols); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } appendToLog("(Pass 2/3) Determining symbol distros per n-gram size..."); iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } iCurCnt = 0; Distribution dSymbolsPerSize = new Distribution(); Distribution dNonSymbolsPerSize = new Distribution(); Distribution dSymbolSizes = new Distribution(); File fPreviousRun = new File(sDistrosFile); boolean bDistrosLoadedOK = false; if (fPreviousRun.exists()) { System.err.println("ATTENTION: Using previous distros..."); try { FileInputStream fis = new FileInputStream(fPreviousRun); ObjectInputStream ois = new ObjectInputStream(fis); dSymbolsPerSize = (Distribution) ois.readObject(); dNonSymbolsPerSize = (Distribution) ois.readObject(); dSymbolSizes = (Distribution) ois.readObject(); ois.close(); bDistrosLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } } if (!bDistrosLoadedOK) while (iIter.hasNext()) { fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal); sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); String sDataString = ""; try { ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); FileInputStream fiIn = new FileInputStream(sFile); int iData = 0; while ((iData = fiIn.read()) > -1) bsOut.write(iData); sDataString = bsOut.toString(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } final Distribution dSymbolsPerSizeArg = dSymbolsPerSize; final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize; final Distribution dSymbolSizesArg = dSymbolSizes; final String sDataStringArg = sDataString; final Set sSymbolsArg = sSymbols; for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) { final int iSymbolSizeArg = iSymbolSize; while (!t.addThreadFor(new Runnable() { public void run() { NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg); ndCur.setDataString(sDataStringArg); int iSymbolCnt = 0; int iNonSymbolCnt = 0; Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator(); while (iExtracted.hasNext()) { String sCur = ((Vertex) iExtracted.next()).toString(); if (sSymbolsArg.contains(sCur)) { iSymbolCnt++; synchronized (dSymbolSizesArg) { dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0); } } else iNonSymbolCnt++; } synchronized (dSymbolsPerSizeArg) { dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt); } synchronized (dNonSymbolsPerSizeArg) { dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt); } } })) Thread.yield(); } } if (!bDistrosLoadedOK) try { t.waitUntilCompletion(); try { FileOutputStream fos = new FileOutputStream(sDistrosFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(dSymbolsPerSize); oos.writeObject(dNonSymbolsPerSize); oos.writeObject(dSymbolSizes); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } } catch (InterruptedException ex) { appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n"); NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize); IntegerPair p = nseEstimator.getOptimalRange(); appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second()); fStatus.setStatus("Determining optimal distance...", 0.0); DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator); int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second()); fStatus.setStatus("Determining optimal distance...", 1.0); appendToLog("\nOptimal distance:" + iBestDist); appendToLog("======DONE=====\n"); } finally { sgOverallGraph.removeNotificationListener(); } }
|
00
|
Code Sample 1:
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; }
Code Sample 2:
public void updateChecksum() { try { MessageDigest md = MessageDigest.getInstance("SHA"); List<Parameter> sortedKeys = new ArrayList<Parameter>(parameter_instances.keySet()); for (Parameter p : sortedKeys) { if (parameter_instances.get(p) != null && !(parameter_instances.get(p) instanceof OptionalDomain.OPTIONS) && !(parameter_instances.get(p).equals(FlagDomain.FLAGS.OFF))) { md.update(parameter_instances.get(p).toString().getBytes()); } } this.checksum = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
private Properties getProperties(URL url) throws java.io.IOException { Properties cdrList = new Properties(); java.io.InputStream stream = url.openStream(); cdrList.load(stream); stream.close(); return cdrList; }
Code Sample 2:
@Override public LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; }
|
00
|
Code Sample 1:
public void sendResponse(DjdocRequest req, HttpServletResponse res) throws IOException { File file = (File) req.getResult(); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) { in.close(); } } }
Code Sample 2:
public static boolean canWeConnectToInternet() { String s = "http://www.google.com/"; URL url = null; boolean can = false; URLConnection conection = null; try { url = new URL(s); } catch (MalformedURLException e) { System.out.println("This should never happend. Error in URL name. URL specified was:" + s + "."); } try { conection = url.openConnection(); conection.connect(); can = true; } catch (IOException e) { can = false; } if (can) { } return can; }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private static String fetchFile(String urlLocation) { try { URL url = new URL(urlLocation); URLConnection conn = url.openConnection(); File tempFile = File.createTempFile("marla", ".jar"); OutputStream os = new FileOutputStream(tempFile); IOUtils.copy(conn.getInputStream(), os); return tempFile.getAbsolutePath(); } catch (IOException ex) { throw new MarlaException("Unable to fetch file '" + urlLocation + "' from server", ex); } }
|
00
|
Code Sample 1:
protected void setupService(MessageContext msgContext) throws Exception { String realpath = msgContext.getStrProp(Constants.MC_REALPATH); String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION); if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION; if ((realpath != null) && (realpath.endsWith(extension))) { String jwsFile = realpath; String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); File f2 = new File(jwsFile); if (!f2.exists()) { throw new FileNotFoundException(rel); } if (rel.charAt(0) == '/') { rel = rel.substring(1); } int lastSlash = rel.lastIndexOf('/'); String dir = null; if (lastSlash > 0) { dir = rel.substring(0, lastSlash); } String file = rel.substring(lastSlash + 1); String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR); if (outdir == null) outdir = "."; if (dir != null) { outdir = outdir + File.separator + dir; } File outDirectory = new File(outdir); if (!outDirectory.exists()) { outDirectory.mkdirs(); } if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile); String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "java"; String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "class"; if (log.isDebugEnabled()) { log.debug("jFile: " + jFile); log.debug("cFile: " + cFile); log.debug("outdir: " + outdir); } File f1 = new File(cFile); String clsName = null; if (clsName == null) clsName = f2.getName(); if (clsName != null && clsName.charAt(0) == '/') clsName = clsName.substring(1); clsName = clsName.substring(0, clsName.length() - extension.length()); clsName = clsName.replace('/', '.'); if (log.isDebugEnabled()) log.debug("ClsName: " + clsName); if (!f1.exists() || f2.lastModified() > f1.lastModified()) { log.debug(Messages.getMessage("compiling00", jwsFile)); log.debug(Messages.getMessage("copy00", jwsFile, jFile)); FileReader fr = new FileReader(jwsFile); FileWriter fw = new FileWriter(jFile); char[] buf = new char[4096]; int rc; while ((rc = fr.read(buf, 0, 4095)) >= 0) fw.write(buf, 0, rc); fw.close(); fr.close(); log.debug("javac " + jFile); Compiler compiler = CompilerFactory.getCompiler(); compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext)); compiler.setDestination(outdir); compiler.addFile(jFile); boolean result = compiler.compile(); (new File(jFile)).delete(); if (!result) { (new File(cFile)).delete(); Document doc = XMLUtils.newDocument(); Element root = doc.createElementNS("", "Errors"); StringBuffer message = new StringBuffer("Error compiling "); message.append(jFile); message.append(":\n"); List errors = compiler.getErrors(); int count = errors.size(); for (int i = 0; i < count; i++) { CompilerError error = (CompilerError) errors.get(i); if (i > 0) message.append("\n"); message.append("Line "); message.append(error.getStartLine()); message.append(", column "); message.append(error.getStartColumn()); message.append(": "); message.append(error.getMessage()); } root.appendChild(doc.createTextNode(message.toString())); throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root }); } ClassUtils.removeClassLoader(clsName); soapServices.remove(clsName); } ClassLoader cl = ClassUtils.getClassLoader(clsName); if (cl == null) { cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile); } msgContext.setClassLoader(cl); SOAPService rpc = (SOAPService) soapServices.get(clsName); if (rpc == null) { rpc = new SOAPService(new RPCProvider()); rpc.setName(clsName); rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName); rpc.setEngine(msgContext.getAxisEngine()); String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS); if (allowed == null) allowed = "*"; rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed); String scope = (String) getOption(RPCProvider.OPTION_SCOPE); if (scope == null) scope = Scope.DEFAULT.getName(); rpc.setOption(RPCProvider.OPTION_SCOPE, scope); rpc.getInitializedServiceDesc(msgContext); soapServices.put(clsName, rpc); } rpc.setEngine(msgContext.getAxisEngine()); rpc.init(); msgContext.setService(rpc); } if (log.isDebugEnabled()) { log.debug("Exit: JWSHandler::invoke"); } }
Code Sample 2:
public static String loadSite(String spec) throws IOException { URL url = new URL(spec); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String output = ""; String str; while ((str = in.readLine()) != null) { output += str + "\n"; } in.close(); return output; }
|
11
|
Code Sample 1:
public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; }
Code Sample 2:
private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
11
|
Code Sample 1:
public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } }
Code Sample 2:
public static List<String> unZip(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream); ZipArchiveEntry entry = in.getNextZipEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextZipEntry(); } in.close(); return result; }
|
00
|
Code Sample 1:
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; }
Code Sample 2:
void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length == 0) { System.out.println("Specify name of the file, just one entry per line"); System.exit(0); } File inFile = new File(args[0]); BufferedReader myBR = null; File outFile = new File(args[0] + ".xml"); BufferedWriter myBW = null; try { myBR = new BufferedReader(new FileReader(inFile)); myBW = new BufferedWriter(new FileWriter(outFile)); } catch (Exception ex) { System.out.println("IN: " + inFile.getAbsolutePath()); System.out.println("OUT: " + outFile.getAbsolutePath()); ex.printStackTrace(); System.exit(0); } try { String readLine; while ((readLine = myBR.readLine()) != null) { myBW.write("<dbColumn name=\"" + readLine + "\" display=\"" + readLine + "\" panel=\"CENTER\" >"); myBW.write("\n"); myBW.write("<dbType name=\"text\" maxVal=\"10\" defaultVal=\"\" sizeX=\"5\"/>"); myBW.write("\n"); myBW.write("</dbColumn>"); myBW.write("\n"); } myBW.close(); myBR.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } System.out.println("OUT: " + outFile.getAbsolutePath()); System.out.println("erzeugt"); }
Code Sample 2:
public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); }
|
11
|
Code Sample 1:
public void testRoundTrip_1(String resource) throws Exception { long start1 = System.currentTimeMillis(); File originalFile = File.createTempFile("RoundTripTest", "testRoundTrip_1"); FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(getClass().getResourceAsStream(resource), fos); fos.close(); long start2 = System.currentTimeMillis(); IsoFile isoFile = new IsoFile(new FileInputStream(originalFile).getChannel()); long start3 = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(baos); long start4 = System.currentTimeMillis(); Walk.through(isoFile); long start5 = System.currentTimeMillis(); isoFile.getBox(wbc); wbc.close(); long start6 = System.currentTimeMillis(); System.err.println("Preparing tmp copy took: " + (start2 - start1) + "ms"); System.err.println("Parsing took : " + (start3 - start2) + "ms"); System.err.println("Writing took : " + (start6 - start3) + "ms"); System.err.println("Walking took : " + (start5 - start4) + "ms"); byte[] a = IOUtils.toByteArray(getClass().getResourceAsStream(resource)); byte[] b = baos.toByteArray(); Assert.assertArrayEquals(a, b); }
Code Sample 2:
private String unzip(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
|
11
|
Code Sample 1:
public static String encodePassword(String password, byte[] seed) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (seed == null) { seed = new byte[12]; secureRandom.nextBytes(seed); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(seed, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new sun.misc.BASE64Encoder().encode(storedPassword); }
Code Sample 2:
protected static byte[] hashPassword(byte[] saltBytes, String plaintextPassword) throws AssertionError { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw (AssertionError) new AssertionError("No MD5 message digest supported.").initCause(ex); } digest.update(saltBytes); try { digest.update(plaintextPassword.getBytes("utf-8")); } catch (UnsupportedEncodingException ex) { throw (AssertionError) new AssertionError("No UTF-8 encoding supported.").initCause(ex); } byte[] passwordBytes = digest.digest(); return passwordBytes; }
|
11
|
Code Sample 1:
private void appendAndDelete(FileOutputStream outstream, String file) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(file); byte[] buffer = new byte[65536]; int l; while ((l = input.read(buffer)) != -1) outstream.write(buffer, 0, l); input.close(); new File(file).delete(); }
Code Sample 2:
private static void copyFile(String fromFile, String toFile) throws Exception { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
private void createProperty(String objectID, String value, String propertyID, Long userID) throws JspTagException { ClassProperty classProperty = new ClassProperty(new Long(propertyID)); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(new Long(propertyID), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } }
Code Sample 2:
public void addUser(String username, String password, String filename) { String data = ""; try { open(filename); MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); data = username + " " + encPasswd + "\r\n"; } try { long length = file.length(); file.seek(length); file.write(data.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } close(); } catch (NoSuchAlgorithmException ex) { } }
|
11
|
Code Sample 1:
@Override protected RequestLogHandler createRequestLogHandler() { try { File logbackConf = File.createTempFile("logback-access", ".xml"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("logback-access.xml"), new FileOutputStream(logbackConf)); RequestLogHandler requestLogHandler = new RequestLogHandler(); RequestLogImpl requestLog = new RequestLogImpl(); requestLog.setFileName(logbackConf.getPath()); requestLogHandler.setRequestLog(requestLog); } catch (FileNotFoundException e) { log.error("Could not create request log handler", e); } catch (IOException e) { log.error("Could not create request log handler", e); } return null; }
Code Sample 2:
private void installBinaryFile(File source, File destination) { byte[] buffer = new byte[8192]; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); int read; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } } catch (FileNotFoundException e) { } catch (IOException e) { new ProjectCreateException(e, "Failed to read binary file: %1$s", source.getAbsolutePath()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public void testReceiveMessageWithHttpPost() throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://192.167.131.126/hotel/sms/create.htm"); String receipt = "2#12345:source:079456345:200:xxx:1234567809:userfred:"; String message = "11796 book owner2 password 238 12.09.2008 3 testname surname"; HttpParams params = new BasicHttpParams(); params.setParameter("TextMessage", message); httpPost.setParams(params); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); }
Code Sample 2:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
|
00
|
Code Sample 1:
@TestTargetNew(level = TestLevel.ADDITIONAL, notes = "", method = "SecureCacheResponse", args = { }) public void test_additional() throws Exception { URL url = new URL("http://google.com"); ResponseCache.setDefault(new TestResponseCache()); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setUseCaches(true); httpCon.connect(); try { Thread.sleep(5000); } catch (Exception e) { } httpCon.disconnect(); }
Code Sample 2:
public static void registerProviders(ResteasyProviderFactory factory) throws Exception { Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName()); LinkedHashSet<String> set = new LinkedHashSet<String>(); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStream is = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.equals("")) continue; set.add(line); } } finally { is.close(); } } for (String line : set) { try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(line); factory.registerProvider(clazz, true); } catch (NoClassDefFoundError e) { logger.warn("NoClassDefFoundError: Unable to load builtin provider: " + line); } catch (ClassNotFoundException e) { logger.warn("ClassNotFoundException: Unable to load builtin provider: " + line); } } }
|
11
|
Code Sample 1:
public static boolean compress(File source, File target, Manifest manifest) { try { if (!(source.exists() & source.isDirectory())) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { File manifestDir = new File(source, "META-INF"); remove(manifestDir); if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); ArrayList list = getContents(source); String baseDir = source.getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
Code Sample 2:
private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } }
Code Sample 2:
public static String plainStringToMD5(String input) { if (input == null) { throw new NullPointerException("Input cannot be null"); } MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
private void init(URL url) { frame = new JInternalFrame(name); frame.addInternalFrameListener(this); listModel.add(listModel.size(), this); area = new JTextArea(); area.setMargin(new Insets(5, 5, 5, 5)); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String in; while ((in = reader.readLine()) != null) { area.append(in); area.append("\n"); } reader.close(); } catch (Exception e) { e.printStackTrace(); return; } th = area.getTransferHandler(); area.setFont(new Font("monospaced", Font.PLAIN, 12)); area.setCaretPosition(0); area.setDragEnabled(true); area.setDropMode(DropMode.INSERT); frame.getContentPane().add(new JScrollPane(area)); dp.add(frame); frame.show(); if (DEMO) { frame.setSize(300, 200); } else { frame.setSize(400, 300); } frame.setResizable(true); frame.setClosable(true); frame.setIconifiable(true); frame.setMaximizable(true); frame.setLocation(left, top); incr(); SwingUtilities.invokeLater(new Runnable() { public void run() { select(); } }); nullItem.addActionListener(this); setNullTH(); }
Code Sample 2:
private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; }
|
00
|
Code Sample 1:
protected void doBackupOrganizeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT organize_id,organize_type_id,child_id,child_type_id,remark " + "FROM " + Common.ORGANIZE_RELATION_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_RELATION_B_TABLE + " " + "(version_no,organize_id,organize_type,child_id,child_type,remark) " + "VALUES (?,?,?,?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("organize_id")); ps.setString(3, result.getString("organize_type_id")); ps.setString(4, result.getString("child_id")); ps.setString(5, result.getString("child_type_id")); ps.setString(6, result.getString("remark")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_RELATION_B INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeRelation(): SQLException while committing or rollback"); } }
Code Sample 2:
public static final void newRead() { HTMLDocument html = new HTMLDocument(); html.putProperty("IgnoreCharsetDirective", new Boolean(true)); try { HTMLEditorKit kit = new HTMLEditorKit(); URL url = new URL("http://omega.rtu.lv/en/index.html"); kit.read(new BufferedReader(new InputStreamReader(url.openStream())), html, 0); Reader reader = new FileReader(html.getText(0, html.getLength())); List<String> links = HTMLUtils.extractLinks(reader); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
Code Sample 2:
public void execute() throws InstallerException { try { SQLCommand sqlCommand = new SQLCommand(connectionInfo); connection = sqlCommand.getConnection(); connection.setAutoCommit(false); sqlStatement = connection.createStatement(); double size = (double) statements.size(); for (String statement : statements) { sqlStatement.executeUpdate(statement); setCompletedPercentage(getCompletedPercentage() + (1 / size)); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new InstallerException(InstallerException.TRANSACTION_ROLLBACK_ERROR, new Object[] { e.getMessage() }, e); } throw new InstallerException(InstallerException.SQL_EXEC_EXCEPTION, new Object[] { e.getMessage() }, e); } catch (ClassNotFoundException e) { throw new InstallerException(InstallerException.DB_DRIVER_LOAD_ERROR, e); } finally { if (connection != null) { try { sqlStatement.close(); connection.close(); } catch (SQLException e) { } } } }
|
11
|
Code Sample 1:
public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); }
Code Sample 2:
public String encrypt(String pstrPlainText) throws Exception { if (pstrPlainText == null) { return ""; } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pstrPlainText.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
|
00
|
Code Sample 1:
private DataSource loadSingleDataSource(ClassLoader contextLoader, URL url) throws IOException, DataSourceException { URI datasourceURI; OWLOntology datasourceOntology = null; URL baseURL = new URL(url.toString().replace("META-INF/artifact.properties", "")); Properties properties = new Properties(); properties.load(url.openStream()); String fileName = properties.get("db").toString() + ".owl"; String pkg = properties.get("package").toString(); datasourceURI = URI.create("http://" + properties.get("host").toString() + "/" + fileName); Set<Class> beans = new HashSet<Class>(); if (baseURL.toString().startsWith("jar") && baseURL.toString().endsWith("!/")) { JarURLConnection jarConn = (JarURLConnection) baseURL.openConnection(); Enumeration<JarEntry> entries = jarConn.getJarFile().entries(); while (entries.hasMoreElements()) { JarEntry next = entries.nextElement(); if (next.getName().startsWith(pkg.replace('.', '/')) && next.getName().endsWith(".class")) { String fullClassName = next.getName().replace('/', '.').replace(".class", ""); try { beans.add(contextLoader.loadClass(fullClassName)); } catch (ClassNotFoundException e) { throw new DataSourceException("Unable to locate " + fullClassName + ".class", e); } } else if (next.getName().equals(fileName)) { String resName = next.getName(); URL owl = contextLoader.getResource(resName); try { datasourceOntology = OWLManager.createOWLOntologyManager().loadOntologyFromPhysicalURI(owl.toURI()); } catch (URISyntaxException e) { throw new DataSourceException("Bad syntax converting url -> uri: " + owl.toString(), e); } catch (OWLOntologyCreationException e) { throw new DataSourceException("Couldn't create ontology from " + owl.toString(), e); } } } if (beans.size() == 0) { throw new DataSourceException("Failed to load beans for the datasource at " + url); } if (datasourceOntology == null) { throw new DataSourceException("The datasource at " + url + " contains no ontology, or the ontology could not be loaded"); } return new BeanModelDataSource(datasourceURI, datasourceOntology); } else { throw new DataSourceException("Unable to create a datasource, cannot load classes with the " + "given URL protocol (" + baseURL + ")"); } }
Code Sample 2:
public void put(IMetaCollection aCollection) throws TransducerException { if (null != ioTransducer) { try { URL urlObj = new URL(url); URLConnection urlConn = urlObj.openConnection(); OutputStreamWriter sw = new OutputStreamWriter(urlConn.getOutputStream()); ioTransducer.setWriter(new BufferedWriter(sw)); ioTransducer.put(aCollection); } catch (Exception e) { throw new TransducerException(e); } } else { throw new TransducerException("An IIOTransducer instance must first be set on the URLTransducerAdapter."); } }
|
00
|
Code Sample 1:
public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
Code Sample 2:
public Graph<N, E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } }
|
00
|
Code Sample 1:
@Override protected Control createDialogArea(final Composite parent) { this.area = new Composite((Composite) super.createDialogArea(parent), SWT.NONE); this.area.setLayout(new FillLayout()); this.area.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); this.scrolledComposite = new ScrolledComposite(this.area, SWT.V_SCROLL | SWT.H_SCROLL); this.scrolledComposite.setLayout(new FillLayout()); this.scrolledComposite.setExpandVertical(true); this.scrolledComposite.setExpandHorizontal(true); ViewForm vf = new ViewForm(this.scrolledComposite, SWT.BORDER | SWT.FLAT); vf.horizontalSpacing = 0; vf.verticalSpacing = 0; ToolBarManager tbm = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL | SWT.RIGHT); long width = InformationUtil.getChildByType(this.image, ImagePlugin.NODE_NAME_WIDTH).getLongValue(); long height = InformationUtil.getChildByType(this.image, ImagePlugin.NODE_NAME_HEIGHT).getLongValue(); this.graphicalViewer = new ScrollingGraphicalViewer(); ScalableRootEditPart root = new ScalableRootEditPart(); this.graphicalViewer.setRootEditPart(root); this.graphicalViewer.setEditDomain(new EditDomain()); this.graphicalViewer.setEditPartFactory(new ImageLinkEditPartFactory(this.editingDomain)); this.canvas = (FigureCanvas) this.graphicalViewer.createControl(vf); this.canvas.getHorizontalBar().setVisible(true); this.canvas.getVerticalBar().setVisible(true); this.graphicalViewer.setContents(this.image); DeleteCommentAction deleteLinkAction = new DeleteCommentAction(this.image); deleteLinkAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)); CreateCommentAction createLinkAction = new CreateCommentAction(this.image); createLinkAction.setEditingDomain(this.editingDomain); deleteLinkAction.setEditingDomain(this.editingDomain); tbm.add(createLinkAction); tbm.add(deleteLinkAction); this.scrolledComposite.setContent(vf); this.graphicalViewer.addSelectionChangedListener(deleteLinkAction); vf.setTopLeft(tbm.createControl(vf)); vf.setContent(this.canvas); GridData gd = new GridData(SWT.BEGINNING, SWT.TOP); gd.widthHint = (int) width; gd.heightHint = (int) height; this.canvas.setLayoutData(gd); vf.addControlListener(new ControlAdapter() { @Override public void controlResized(final ControlEvent e) { CommentImageDialog.this.canvas.redraw(); super.controlResized(e); } }); setTitle(Messages.CommentImageDialog_Title); setMessage(Messages.CommentImageDialog_Message); setTitleImage(ResourceManager.getPluginImage(ImagePlugin.getDefault(), "icons/iconexperience/comment_wizard_title.png")); return this.area; }
Code Sample 2:
private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } if (!ftp.login(ftpUsername, ftpPassword)) { return null; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
|
00
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private List parseUrlGetUids(String url) throws FetchError { List hids = new ArrayList(); try { InputStream is = (new URL(url)).openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String inputLine = ""; Pattern pattern = Pattern.compile("\\<input\\s+type=hidden\\s+name=hid\\s+value=(\\d+)\\s?\\>", Pattern.CASE_INSENSITIVE); while ((inputLine = in.readLine()) != null) { Matcher matcher = pattern.matcher(inputLine); if (matcher.find()) { String id = matcher.group(1); if (!hids.contains(id)) { hids.add(id); } } } } catch (Exception e) { System.out.println(e); throw new FetchError(e); } return hids; }
|
00
|
Code Sample 1:
private void gerarComissao() { int opt = Funcoes.mensagemConfirma(null, "Confirma gerar comiss�es para o vendedor " + txtNomeVend.getVlrString().trim() + "?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPCOMISSAO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("CODEMPVD, CODFILIALVD, CODVEND, VLRCOMISS ) "); insert.append("VALUES "); insert.append("(?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; boolean gerou = false; try { for (int i = 0; i < tab.getNumLinhas(); i++) { if (((BigDecimal) tab.getValor(i, 8)).floatValue() > 0) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPCOMISSAO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPVENDEDOR")); ps.setInt(parameterIndex++, txtCodVend.getVlrInteger()); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.executeUpdate(); gerou = true; } } if (gerou) { Funcoes.mensagemInforma(null, "Comiss�o gerada para " + txtNomeVend.getVlrString().trim()); txtCodPed.setText("0"); lcPedido.carregaDados(); carregaTabela(); con.commit(); } else { Funcoes.mensagemInforma(null, "N�o foi possiv�l gerar comiss�o!\nVerifique os valores das comiss�es dos itens."); } } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar comiss�o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } }
Code Sample 2:
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getJarFileURL", args = { }) public void test_getJarFileURL() throws Exception { URL u = createContent("lf.jar", "plus.bmp"); URL fileURL = new URL(u.getPath().substring(0, u.getPath().indexOf("!"))); juc = (JarURLConnection) u.openConnection(); assertTrue("Returned incorrect file URL", juc.getJarFileURL().equals(fileURL)); URL url = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class"); assertEquals("file:/bar.jar", ((JarURLConnection) url.openConnection()).getJarFileURL().toString()); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); }
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(); } }
|
00
|
Code Sample 1:
public ResponseStatus nowPlaying(String artist, String track, String album, int length, int tracknumber) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); String b = album != null ? encode(album) : ""; String l = length == -1 ? "" : String.valueOf(length); String n = tracknumber == -1 ? "" : String.valueOf(tracknumber); String body = String.format("s=%s&a=%s&t=%s&b=%s&l=%s&n=%s&m=", sessionId, encode(artist), encode(track), b, l, n); if (Caller.getInstance().isDebugMode()) System.out.println("now playing: " + body); Proxy proxy = Caller.getInstance().getProxy(); HttpURLConnection urlConnection = Caller.getInstance().openConnection(nowPlayingUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); return new ResponseStatus(ResponseStatus.codeForStatus(status)); }
Code Sample 2:
private static void identify(ContentNetwork cn, String str) { try { URL url = new URL(str); HttpURLConnection con = (HttpURLConnection) url.openConnection(); UrlUtils.setBrowserHeaders(con, null); String key = "cn." + cn.getID() + ".identify.cookie"; String cookie = COConfigurationManager.getStringParameter(key, null); if (cookie != null) { con.setRequestProperty("Cookie", cookie + ";"); } con.setRequestProperty("Connection", "close"); con.getResponseCode(); cookie = con.getHeaderField("Set-Cookie"); if (cookie != null) { String[] bits = cookie.split(";"); if (bits.length > 0 && bits[0].length() > 0) { COConfigurationManager.setParameter(key, bits[0]); } } } catch (Throwable e) { } }
|
00
|
Code Sample 1:
public void deleteScript(Integer id) { InputStream is = null; try { URL url = new URL(strServlet + getSessionIDSuffix() + "?deleteScript=" + id); System.out.println("requesting: " + url); is = url.openStream(); while (is.read() != -1) ; } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (Exception e) { } } }
Code Sample 2:
public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load " + name); return classList; } while (services.hasMoreElements()) { URL url = (URL) services.nextElement(); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: " + url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: " + url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String) names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: " + className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: " + className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: " + className); } catch (NoClassDefFoundError e) { System.err.println("Service: " + e + " for " + className); } catch (Exception e) { System.err.println("Service: exception for: " + className + " " + e); } } return classList; }
|
00
|
Code Sample 1:
public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } }
Code Sample 2:
public static String send(String ipStr, int port, String password, String command, InetAddress localhost, int localPort) throws SocketTimeoutException, BadRcon, ResponseEmpty { StringBuffer response = new StringBuffer(); try { rconSocket = new Socket(); rconSocket.bind(new InetSocketAddress(localhost, localPort)); rconSocket.connect(new InetSocketAddress(ipStr, port), RESPONSE_TIMEOUT); out = rconSocket.getOutputStream(); in = rconSocket.getInputStream(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(in)); rconSocket.setSoTimeout(RESPONSE_TIMEOUT); String digestSeed = ""; boolean loggedIn = false; boolean keepGoing = true; while (keepGoing) { String receivedContent = buffRead.readLine(); if (receivedContent.startsWith("### Digest seed: ")) { digestSeed = receivedContent.substring(17, receivedContent.length()); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(digestSeed.getBytes()); md5.update(password.getBytes()); String digestStr = "login " + digestedToHex(md5.digest()) + "\n"; out.write(digestStr.getBytes()); } catch (NoSuchAlgorithmException e1) { response.append("MD5 algorithm not available - unable to complete RCON request."); keepGoing = false; } } else if (receivedContent.startsWith("error: not authenticated: you can only invoke 'login'")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication failed.")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication successful, rcon ready.")) { keepGoing = false; loggedIn = true; } } if (loggedIn) { String cmd = "exec " + command + "\n"; out.write(cmd.getBytes()); readResponse(buffRead, response); if (response.length() == 0) { throw new ResponseEmpty(); } } } catch (SocketTimeoutException timeout) { throw timeout; } catch (UnknownHostException e) { response.append("UnknownHostException: " + e.getMessage()); } catch (IOException e) { response.append("Couldn't get I/O for the connection: " + e.getMessage()); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (rconSocket != null) { rconSocket.close(); } } catch (IOException e1) { } } return response.toString(); }
|
00
|
Code Sample 1:
public void test_filecluster() throws Exception { Configuration.init(); LruPersistentManager sessionManager2 = new LruPersistentManager(new File("d:/temp/test")); TomcatServer ts2 = new TomcatServer("hf1", sessionManager2); ts2.registerServlet("/*", TestServlet.class.getName()); ts2.start(5556); LruPersistentManager sessionManager1 = new LruPersistentManager(new File("d:/temp/test")); TomcatServer ts1 = new TomcatServer("hf2", sessionManager1); ts1.registerServlet("/*", TestServlet.class.getName()); ts1.start(5555); URL url1 = new URL("http://127.0.0.1:5555/a"); HttpURLConnection c1 = (HttpURLConnection) url1.openConnection(); assert getData(c1).equals("a null"); String cookie = c1.getHeaderField("Set-Cookie"); Thread.sleep(10000); URL url2 = new URL("http://127.0.0.1:5556/a"); HttpURLConnection c2 = (HttpURLConnection) url2.openConnection(); c2.setRequestProperty("Cookie", cookie); assert getData(c2).equals("a a"); Thread.sleep(15000); }
Code Sample 2:
protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method); request.setDoOutput(true); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream())); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } }
|
11
|
Code Sample 1:
public static String MD5ToString(String md5) { String hashword = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(md5.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
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 testIntegrityViolation() throws Exception { if (getDialect() instanceof MySQLMyISAMDialect) { reportSkip("MySQL (ISAM) does not support FK violation checking", "exception conversion"); return; } SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); Session session = openSession(); session.beginTransaction(); Connection connection = session.connection(); PreparedStatement ps = null; try { ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"); ps.setLong(1, 52134241); ps.setLong(2, 5342); ps.executeUpdate(); fail("INSERT should have failed"); } catch (SQLException sqle) { JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!"); JDBCException jdbcException = converter.convert(sqle, null, null); assertEquals("Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class, jdbcException.getClass()); ConstraintViolationException ex = (ConstraintViolationException) jdbcException; System.out.println("Violated constraint name: " + ex.getConstraintName()); } finally { if (ps != null) { try { ps.close(); } catch (Throwable ignore) { } } } session.getTransaction().rollback(); session.close(); }
Code Sample 2:
@Test public void test_blueprintTypeByTypeID_NonExistingID() throws Exception { URL url = new URL(baseUrl + "/blueprintTypeByTypeID/1234567890"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); XSLTBuddy buddy = new XSLTBuddy(); buddy.parseArgs(args); XSLTransformer transformer = new XSLTransformer(); if (buddy.templateDir != null) { transformer.setTemplateDir(buddy.templateDir); } FileReader xslReader = new FileReader(buddy.xsl); Templates xslTemplate = transformer.getXSLTemplate(buddy.xsl, xslReader); for (Enumeration e = buddy.params.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); transformer.addParam(key, buddy.params.get(key)); } Reader reader = null; if (buddy.src == null) { reader = new StringReader(XSLTBuddy.BLANK_XML); } else { reader = new FileReader(buddy.src); } if (buddy.out == null) { String result = transformer.doTransform(reader, xslTemplate, buddy.xsl); buddy.getLogger().info("\n\nXSLT Result:\n\n" + result + "\n"); } else { File file = new File(buddy.out); File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); } FileWriter writer = new FileWriter(buddy.out); transformer.doTransform(reader, xslTemplate, buddy.xsl, writer); writer.flush(); writer.close(); } buddy.getLogger().info("Transform done successfully in " + (System.currentTimeMillis() - start) + " milliseconds"); }
Code Sample 2:
public static void copyFile(File in, File out) { if (!in.exists() || !in.canRead()) { LOGGER.warn("Can't copy file : " + in); return; } if (!out.getParentFile().exists()) { if (!out.getParentFile().mkdirs()) { LOGGER.info("Didn't create parent directories : " + out.getParentFile().getAbsolutePath()); } } if (!out.exists()) { try { out.createNewFile(); } catch (IOException e) { LOGGER.error("Exception creating new file : " + out.getAbsolutePath(), e); } } LOGGER.debug("Copying file : " + in + ", to : " + out); FileChannel inChannel = null; FileChannel outChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(in); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(out); outChannel = fileOutputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { LOGGER.error("Exception copying file : " + in + ", to : " + out, e); } finally { close(fileInputStream); close(fileOutputStream); if (inChannel != null) { try { inChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing input channel : ", e); } } if (outChannel != null) { try { outChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing output channel : ", e); } } } }
|
00
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
void getAddress(String lat, String lag) { try { URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q=" + lat + "," + lag); InputStream inputStream = url.openConnection().getInputStream(); InputStreamReader inputReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufReader = new BufferedReader(inputReader); String line = "", lines = ""; while ((line = bufReader.readLine()) != null) { lines += line; } if (!lines.equals("")) { JSONObject jsonobject = new JSONObject(lines); JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString()); for (int i = 0; i < jsonArray.length(); i++) { mTextView.setText(mTextView.getText() + "\n" + jsonArray.getJSONObject(i).getString("address")); } } } catch (Exception e) { ; } }
|
00
|
Code Sample 1:
@SuppressWarnings("rawtypes") public static String[] loadAllPropertiesFromClassLoader(Properties properties, String... resourceNames) throws IOException { List successLoadProperties = new ArrayList(); for (String resourceName : resourceNames) { URL url = GeneratorProperties.class.getResource(resourceName); if (url != null) { successLoadProperties.add(url.getFile()); InputStream input = null; try { URLConnection con = url.openConnection(); con.setUseCaches(false); input = con.getInputStream(); if (resourceName.endsWith(".xml")) { properties.loadFromXML(input); } else { properties.load(input); } } finally { if (input != null) { input.close(); } } } } return (String[]) successLoadProperties.toArray(new String[0]); }
Code Sample 2:
public static final String crypt(String password, String salt) throws NoSuchAlgorithmException { String magic = "$1$"; byte finalState[]; MessageDigest ctx, ctx1; long l; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx = MessageDigest.getInstance("MD5"); ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1 = MessageDigest.getInstance("MD5"); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { for (int i = 0; i < (pl > 16 ? 16 : pl); i++) ctx.update(finalState[i]); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState[0]); } else { ctx.update(password.getBytes()[0]); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { ctx1 = MessageDigest.getInstance("MD5"); if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); }
|
00
|
Code Sample 1:
protected IRunnableWithProgress getProjectCreationRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; monitor.beginTask("New Modulo Project Creation", remainingWorkUnits); IWorkspace ws = ResourcesPlugin.getWorkspace(); newProject = fMainPage.getProjectHandle(); IProjectDescription description = ws.newProjectDescription(newProject.getName()); String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID }; description.setNatureIds(natures); ICommand command = description.newCommand(); command.setBuilderName(JavaCore.BUILDER_ID); ICommand[] commands = { command }; description.setBuildSpec(commands); IJavaProject jproject = JavaCore.create(newProject); ModuloProject modProj = new ModuloProject(); modProj.setJavaProject(jproject); try { newProject.create(description, new SubProgressMonitor(monitor, 1)); newProject.open(new SubProgressMonitor(monitor, 1)); IFolder srcFolder = newProject.getFolder("src"); IFolder javaFolder = srcFolder.getFolder("java"); IFolder buildFolder = newProject.getFolder("build"); IFolder classesFolder = buildFolder.getFolder("classes"); modProj.createFolder(srcFolder); modProj.createFolder(javaFolder); modProj.createFolder(buildFolder); modProj.createFolder(classesFolder); IPath buildPath = newProject.getFolder("build/classes").getFullPath(); jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) }; jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); ModuleDefinition definition = new ModuleDefinition(); definition.setId(fModuloPage.getPackageName()); definition.setVersion(new VersionNumber(1, 0, 0)); definition.setMetaName(fModuloPage.getModuleName()); definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module."); definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName()); if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName()); if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName()); modProj.setDefinition(definition); modProj.createPackage(); modProj.createModuleXML(); modProj.createMainClass(); if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass(); if (fModuloPage.isStatSelectioned()) modProj.createStatClass(); modProj.createModuleProperties(); modProj.createMessagesProperties(); IFolder binFolder = newProject.getFolder("bin"); binFolder.delete(true, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { e.printStackTrace(); } finally { monitor.done(); } } }; }
Code Sample 2:
private static void identify(ContentNetwork cn, String str) { try { URL url = new URL(str); HttpURLConnection con = (HttpURLConnection) url.openConnection(); UrlUtils.setBrowserHeaders(con, null); String key = "cn." + cn.getID() + ".identify.cookie"; String cookie = COConfigurationManager.getStringParameter(key, null); if (cookie != null) { con.setRequestProperty("Cookie", cookie + ";"); } con.setRequestProperty("Connection", "close"); con.getResponseCode(); cookie = con.getHeaderField("Set-Cookie"); if (cookie != null) { String[] bits = cookie.split(";"); if (bits.length > 0 && bits[0].length() > 0) { COConfigurationManager.setParameter(key, bits[0]); } } } catch (Throwable e) { } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
Code Sample 2:
public void compressImage(InputStream input, String output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile; try { inputFile = File.createTempFile("tmp", ".tif"); inputFile.deleteOnExit(); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } compressImage(inputFile.getAbsolutePath(), output, params); if (inputFile != null) inputFile.delete(); }
|
00
|
Code Sample 1:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
@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); }
|
11
|
Code Sample 1:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
00
|
Code Sample 1:
public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; }
Code Sample 2:
public static Set<String> getProteins(final String goCode, final Set<String> evCodes, final int taxon, final int limit) throws IOException { final Set<String> proteins = new HashSet<String>(); HttpURLConnection connection = null; try { final String evCodeList = join(evCodes); final URL url = new URL(String.format(__urlTempl4, goCode, evCodeList, taxon, limit + 1)); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(__connTimeout); connection.setReadTimeout(__readTimeout); connection.setRequestProperty("Connection", "close"); connection.connect(); final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = br.readLine()) != null) { proteins.add(line.trim()); } } finally { if (connection != null) connection.disconnect(); } return filter(proteins); }
|
11
|
Code Sample 1:
public File convert(URI uri) throws DjatokaException { processing.add(uri.toString()); File urlLocal = null; try { logger.info("processingRemoteURI: " + uri.toURL()); boolean isJp2 = false; InputStream src = IOUtils.getInputStream(uri.toURL()); String ext = uri.toURL().toString().substring(uri.toURL().toString().lastIndexOf(".") + 1).toLowerCase(); if (ext.equals(FORMAT_ID_TIF) || ext.equals(FORMAT_ID_TIFF)) { urlLocal = File.createTempFile("convert" + uri.hashCode(), "." + FORMAT_ID_TIF); } else if (formatMap.containsKey(ext) && (formatMap.get(ext).equals(FORMAT_MIMEYPE_JP2) || formatMap.get(ext).equals(FORMAT_MIMEYPE_JPX))) { urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + ext); isJp2 = true; } else { if (src.markSupported()) src.mark(15); if (ImageProcessingUtils.checkIfJp2(src)) urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + FORMAT_ID_JP2); if (src.markSupported()) src.reset(); else { src.close(); src = IOUtils.getInputStream(uri.toURL()); } } if (urlLocal == null) { urlLocal = File.createTempFile("convert" + uri.hashCode(), ".img"); } urlLocal.deleteOnExit(); FileOutputStream dest = new FileOutputStream(urlLocal); IOUtils.copyStream(src, dest); if (!isJp2) urlLocal = processImage(urlLocal, uri); src.close(); dest.close(); return urlLocal; } catch (Exception e) { urlLocal.delete(); throw new DjatokaException(e); } finally { if (processing.contains(uri.toString())) processing.remove(uri.toString()); } }
Code Sample 2:
public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
|
11
|
Code Sample 1:
protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; }
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:
private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; }
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 boolean createFTPConnection() { client = new FTPClient(); System.out.println("Client created"); try { client.connect(this.hostname, this.port); System.out.println("Connected: " + this.hostname + ", " + this.port); client.login(username, password); System.out.println("Logged in: " + this.username + ", " + this.password); this.setupActiveFolder(); return true; } catch (IllegalStateException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPIllegalReplyException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } return false; }
Code Sample 2:
@Override public void execute() throws BuildException { if (this.toFile == null && this.toDir == null) throw new BuildException("Missing Destination File/Dir"); if (this.toFile != null && this.toDir != null) throw new BuildException("Both Defined Destination File/Dir"); if (this.urlStr == null) throw new BuildException("Missing URL"); URL base = null; try { if (baseStr != null) base = new URL(this.baseStr + (baseStr.endsWith("/") ? "" : "/")); } catch (MalformedURLException e) { throw new BuildException(e); } String tokens[] = this.urlStr.split("[ \t\n]+"); try { for (String nextURL : tokens) { nextURL = nextURL.trim(); if (nextURL.length() == 0) continue; URL url = null; try { url = new URL(base, nextURL); } catch (MalformedURLException e) { throw new BuildException(e); } File dest = null; if (this.toDir != null) { String file = url.getFile(); int i = file.lastIndexOf('/'); if (i != -1 && i + 1 != file.length()) file = file.substring(i + 1); dest = new File(this.toDir, file); } else { dest = this.toFile; } if (dest.exists()) continue; byte buff[] = new byte[2048]; FileOutputStream out = new FileOutputStream(dest); InputStream in = url.openStream(); int n = 0; while ((n = in.read(buff)) != -1) { out.write(buff, 0, n); } in.close(); out.flush(); out.close(); System.out.println("Downloaded " + url + " to " + dest); } } catch (IOException e) { throw new BuildException(e); } }
|
00
|
Code Sample 1:
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); } } }
Code Sample 2:
@Override public String getMD5(String host) { String res = ""; Double randNumber = Math.random() + System.currentTimeMillis(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(randNumber.toString().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 (Exception ex) { } return res; }
|
11
|
Code Sample 1:
@SuppressWarnings("unchecked") private void appendAttachments(final Part part) throws MessagingException, IOException { if (part.isMimeType("message/*")) { JcrMessage jcrMessage = new JcrMessage(); Message attachedMessage = null; if (part.getContent() instanceof Message) { attachedMessage = (Message) part.getContent(); } else { attachedMessage = new MStorMessage(null, (InputStream) part.getContent()); } jcrMessage.setFlags(attachedMessage.getFlags()); jcrMessage.setHeaders(attachedMessage.getAllHeaders()); jcrMessage.setReceived(attachedMessage.getReceivedDate()); jcrMessage.setExpunged(attachedMessage.isExpunged()); jcrMessage.setMessage(attachedMessage); messages.add(jcrMessage); } else if (part.isMimeType("multipart/*")) { Multipart multi = (Multipart) part.getContent(); for (int i = 0; i < multi.getCount(); i++) { appendAttachments(multi.getBodyPart(i)); } } else if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotEmpty(part.getFileName())) { JcrFile attachment = new JcrFile(); String name = null; if (StringUtils.isNotEmpty(part.getFileName())) { name = part.getFileName(); for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { return; } } } else { String[] contentId = part.getHeader("Content-Id"); if (contentId != null && contentId.length > 0) { name = contentId[0]; } else { name = "attachment"; } } int count = 0; for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { count++; } } if (count > 0) { name += "_" + count; } attachment.setName(name); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); attachment.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); attachment.setMimeType(part.getContentType()); attachment.setLastModified(java.util.Calendar.getInstance()); attachments.add(attachment); } }
Code Sample 2:
public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
|
11
|
Code Sample 1:
public static List<String> extract(String zipFilePath, String destDirPath) throws IOException { List<String> list = null; ZipFile zip = new ZipFile(zipFilePath); try { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destFile = new File(destDirPath, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { InputStream in = zip.getInputStream(entry); OutputStream out = new FileOutputStream(destFile); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { out.close(); } catch (IOException ioe) { ioe.getMessage(); } try { in.close(); } catch (IOException ioe) { ioe.getMessage(); } } } if (list == null) { list = new ArrayList<String>(); } list.add(destFile.getAbsolutePath()); } return list; } finally { try { zip.close(); } catch (Exception e) { e.getMessage(); } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private 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 void main(String[] args) throws Exception { File rootDir = new File("C:\\dev\\workspace_fgd\\gouvqc_crggid\\WebContent\\WEB-INF\\upload"); File storeDir = new File(rootDir, "storeDir"); File workDir = new File(rootDir, "workDir"); LoggerFacade loggerFacade = new CommonsLoggingLogger(logger); final FileResourceManager frm = new SmbFileResourceManager(storeDir.getPath(), workDir.getPath(), true, loggerFacade); frm.start(); final String resourceId = "811375c8-7cae-4429-9a0e-9222f47dab45"; { if (!frm.resourceExists(resourceId)) { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); FileInputStream inputStream = new FileInputStream(resourceId); frm.createResource(txId, resourceId); OutputStream outputStream = frm.writeResource(txId, resourceId); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); frm.prepareTransaction(txId); frm.commitTransaction(txId); } } for (int i = 0; i < 30; i++) { final int index = i; new Thread() { @Override public void run() { try { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); InputStream inputStream = frm.readResource(resourceId); frm.prepareTransaction(txId); frm.commitTransaction(txId); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (début)"); } String contenu = TikaUtils.getParsedContent(inputStream, "file.pdf"); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (fin)"); } } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } catch (ResourceManagerException e) { throw new RuntimeException(e); } catch (TikaException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); } Thread.sleep(60000); frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); }
|
00
|
Code Sample 1:
public static Map getResources(String jarFileName, String resource, int port, String protocol) throws Exception { Hashtable content = new Hashtable(); if (!(protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("file"))) throw new IllegalArgumentException("Unsupported protocol; supported is: file or http"); URL url = new URL(protocol, InetAddress.getLocalHost().getHostName(), port, jarFileName); BufferedInputStream bis = new BufferedInputStream(url.openStream()); JarInputStream zipIs = new JarInputStream(bis); ZipEntry entry; int size = 0; Vector v = new Vector(); try { while ((entry = zipIs.getNextEntry()) != null) { Console.log(entry.getName() + ", " + entry.getSize() + "..." + entry.toString()); content.put(entry.getName(), new ZipEntry(entry)); v.add(entry); } } catch (IOException e) { e.printStackTrace(); } ZipEntry ze = null; for (int i = 0; i < v.size(); i++) { ZipEntry zipEntry = (ZipEntry) v.elementAt(i); if (zipEntry.getName().equals(resource)) { ze = zipEntry; break; } } size = (int) ze.getSize(); Console.log("resource size=" + size); byte[] buf = new byte[size]; int rb = 0; int chunk = 0; while ((size - rb) > 0) { chunk = zipIs.read(buf); Console.log("chunk = " + chunk + ", rb=" + rb); if (chunk == -1) { break; } rb += chunk; } try { zipIs.close(); bis.close(); url = null; } catch (IOException e) { Console.log("error closing jar " + e.getMessage()); e.printStackTrace(); } if (size != buf.length) throw new Exception("Resource '" + resource + "' has not been read correctly."); System.out.println("buf=" + buf); content.put(resource, buf); return content; }
Code Sample 2:
public static String encrypt32(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); System.out.println("result: " + buf.toString()); System.out.println("result: " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return str; } return str; }
|
11
|
Code Sample 1:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
Code Sample 2:
public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.