label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private static String digest(String buffer) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(buffer.getBytes()); return new String(encodeHex(md5.digest(key))); } catch (NoSuchAlgorithmException e) { } return null; } Code Sample 2: public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); }
00
Code Sample 1: public static void main(String[] args) { File container = new File(ArchiveFeature.class.getProtectionDomain().getCodeSource().getLocation().toURI()); if (container == null) { throw new RuntimeException("this use-case isn't being invoked from the executable jar"); } JarFile jarFile = new JarFile(container); String artifactName = PROJECT_DIST_ARCHIVE + ".tar.gz"; File artifactFile = new File(".", artifactName); ZipEntry artifactEntry = jarFile.getEntry(artifactName); InputStream source = jarFile.getInputStream(artifactEntry); try { FileOutputStream dest = new FileOutputStream(artifactFile); try { IOUtils.copy(source, dest); } finally { IOUtils.closeQuietly(dest); } } finally { IOUtils.closeQuietly(source); } Project project = new Project(); project.setName("project"); project.init(); Target target = new Target(); target.setName("target"); project.addTarget(target); project.addBuildListener(new Log4jListener()); Untar untar = new Untar(); untar.setTaskName("untar"); untar.setSrc(artifactFile); untar.setDest(new File(".")); Untar.UntarCompressionMethod method = new Untar.UntarCompressionMethod(); method.setValue("gzip"); untar.setCompression(method); untar.setProject(project); untar.setOwningTarget(target); target.addTask(untar); untar.execute(); } Code Sample 2: public InputSource resolveEntity(String publicId, String systemId) { allowXMLCatalogPI = false; String resolved = catalogResolver.getResolvedEntity(publicId, systemId); if (resolved == null && piCatalogResolver != null) { resolved = piCatalogResolver.getResolvedEntity(publicId, systemId); } if (resolved != null) { try { InputSource iSource = new InputSource(resolved); iSource.setPublicId(publicId); URL url = new URL(resolved); InputStream iStream = url.openStream(); iSource.setByteStream(iStream); return iSource; } catch (Exception e) { catalogManager.debug.message(1, "Failed to create InputSource", resolved); return null; } } else { return null; } }
11
Code Sample 1: public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[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(); } Code Sample 2: String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
00
Code Sample 1: public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("H:\\FileServeUploader.java"); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", uprandcookie + ";" + autologincookie); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("MAX_FILE_SIZE", new StringBody("2097152000")); mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid)); mpEntity.addPart("go", new StringBody("1")); mpEntity.addPart("files", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into depositfiles..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); downloadlink = parseResponse(uploadresponse, "ud_download_url = '", "'"); deletelink = parseResponse(uploadresponse, "ud_delete_url = '", "'"); System.out.println("download link : " + downloadlink); System.out.println("delete link : " + deletelink); } } Code Sample 2: @Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtils.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, compareResponse.getMessage(), compareResponse.getControls()); }
00
Code Sample 1: public Map load() throws IOException { rpdMap = new HashMap(); try { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader xr = factory.newSAXParser().getXMLReader(); ConfigHandler handler = new ConfigHandler(); xr.setContentHandler(handler); xr.setErrorHandler(handler); InputStream is = url.openStream(); xr.parse(new InputSource(is)); is.close(); } catch (SAXParseException e) { String msg = "Error while parsing line " + e.getLineNumber() + " of " + url + ": " + e.getMessage(); throw new IOException(msg); } catch (SAXException e) { throw new IOException("Problem with XML: " + e); } catch (ParserConfigurationException e) { throw new IOException(e.getMessage()); } return rpdMap; } Code Sample 2: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); }
11
Code Sample 1: public static String md5String(String string) { try { MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(string.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); String result = ""; for (int i = 0; i < digest.length; i++) { int value = digest[i]; if (value < 0) value += 256; result += Integer.toHexString(value); } return result; } catch (UnsupportedEncodingException error) { throw new IllegalArgumentException(error); } catch (NoSuchAlgorithmException error) { throw new IllegalArgumentException(error); } } Code Sample 2: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } }
00
Code Sample 1: public static boolean verifyPassword(String digest, String password) { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } try { MessageDigest sha = MessageDigest.getInstance(alg); if (sha == null) { return false; } byte[][] hs = split(Base64.decode(digest), size); byte[] hash = hs[0]; byte[] salt = hs[1]; sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); return MessageDigest.isEqual(hash, pwhash); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } } Code Sample 2: public static BufferedReader getUserInfoStream(String name) throws IOException { BufferedReader in; try { URL url = new URL("http://www.spoj.pl/users/" + name.toLowerCase() + "/"); in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException e) { in = null; throw e; } return in; }
11
Code Sample 1: private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestPath = req.getRequestURI(); String cdecUrl = "http://cdec.water.ca.gov" + requestPath + "?" + req.getQueryString(); System.out.println("CDEC URL: " + cdecUrl); URL url = new URL(cdecUrl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); String line = null; int ncolumnInner = 0; while ((line = reader.readLine()) != null) { if (line.contains("<div class=\"column_inner\"")) { ncolumnInner++; } if (ncolumnInner == 2) { if (line.contains("</div>")) { break; } if (line.contains("href")) { line = line.replaceAll("href", " target=\"external_page\" href"); } if (line.contains("http://cdec.water.ca.gov:80")) { line = line.replaceAll("http://cdec.water.ca.gov:80/", "/"); } if (line.contains("href=")) { line = line.replaceAll("(href=\"|href=)", "$1http://cdec.water.ca.gov"); } buffer.append(line); } else { continue; } } resp.getWriter().write(buffer.toString()); resp.getWriter().flush(); reader.close(); } Code Sample 2: public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception { URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid()); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; boolean chargerLyrics = false; StringBuffer sb = new StringBuffer(""); String lyrics = null; while ((ligne = br.readLine()) != null) { log.debug("==> " + ligne); if (chargerLyrics && ligne.indexOf("<center>") != -1) { break; } if (chargerLyrics) { sb.append(ligne.trim()); } if (!chargerLyrics && ligne.indexOf("<center>") != -1) { chargerLyrics = true; } } lyrics = sb.toString(); lyrics = lyrics.replaceAll("<br>", "\n").trim(); log.debug("Parole : " + lyrics); tb.setLyrics(lyrics); br.close(); httpStream.close(); }
11
Code Sample 1: @SuppressWarnings("unchecked") public static void main(String[] args) { System.out.println("Starting encoding test...."); Properties p = new Properties(); try { InputStream pStream = ClassLoader.getSystemResourceAsStream("sample_weather.properties"); p.load(pStream); } catch (Exception e) { System.err.println("Could not load properties file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } if (WeatherUpdater.DEBUG) { System.out.println("hostname: " + p.getProperty("weather.hostname")); } if (WeatherUpdater.DEBUG) { System.out.println("database: " + p.getProperty("weather.database")); } if (WeatherUpdater.DEBUG) { System.out.println("username: " + p.getProperty("weather.username")); } if (WeatherUpdater.DEBUG) { System.out.println("password: " + p.getProperty("weather.password")); } SqlAccount sqlAccount = new SqlAccount(p.getProperty("weather.hostname"), p.getProperty("weather.database"), p.getProperty("weather.username"), p.getProperty("weather.password")); DatabaseInterface dbi = null; try { dbi = new DatabaseInterface(sqlAccount); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Established connection to database."); String query = "SELECT * FROM Current_Weather WHERE ZipCode = '99702'"; ResultTable results; System.out.println("Executing query: " + query); try { results = dbi.executeQuery(query); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Got results from query."); System.out.println("Converted results into the following table:"); System.out.println(results); System.out.println(); Class<? extends ResultEncoder> encoder_class; Class<? extends ResultDecoder> decoder_class; try { encoder_class = (Class<? extends ResultEncoder>) Class.forName(p.getProperty("mysms.coding.resultEncoder")); decoder_class = (Class<? extends ResultDecoder>) Class.forName(p.getProperty("mysms.coding.resultDecoder")); } catch (Exception e) { System.err.println("Could not find specified encoder: " + p.getProperty("result.encoder")); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Found class of encoder: " + encoder_class); System.out.println("Found class of decoder: " + decoder_class); ResultEncoder encoder; ResultDecoder decoder; try { encoder = encoder_class.newInstance(); if (encoder_class.equals(decoder_class) && decoder_class.isInstance(encoder)) { decoder = (ResultDecoder) encoder; } else { decoder = decoder_class.newInstance(); } } catch (Exception e) { System.err.println("Could not create instances of encoder and decoder."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Created instances of encoder and decoder."); if (decoder.equals(encoder)) { System.out.println("Decoder and encoder are same object."); } ByteBuffer buffer; try { buffer = encoder.encode(null, results); } catch (Exception e) { System.err.println("Could not encode results."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Encoded results to ByteBuffer with size: " + buffer.capacity()); File temp; try { temp = File.createTempFile("encoding_test", ".results"); temp.deleteOnExit(); FileChannel out = new FileOutputStream(temp).getChannel(); out.write(buffer); out.close(); } catch (Exception e) { System.err.println("Could not write buffer to file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Wrote buffer to file: \"" + temp.getName() + "\" with length: " + temp.length()); ByteBuffer re_buffer; try { FileInputStream in = new FileInputStream(temp.getAbsolutePath()); byte[] temp_buffer = new byte[(int) temp.length()]; int totalRead = 0; int numRead = 0; while (totalRead < temp_buffer.length) { numRead = in.read(temp_buffer, totalRead, temp_buffer.length - totalRead); if (numRead < 0) { break; } else { totalRead += numRead; } } re_buffer = ByteBuffer.wrap(temp_buffer); in.close(); } catch (Exception e) { System.err.println("Could not read from temporary file into buffer."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Read file back into buffer with length: " + re_buffer.capacity()); ResultTable re_results; try { re_results = decoder.decode(null, re_buffer); } catch (Exception e) { System.err.println("Could not decode buffer into a ResultTable."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Decoded buffer back into the following table:"); System.out.println(re_results); System.out.println(); System.out.println("... encoding test complete."); } Code Sample 2: public void runDynusT() { final String[] exeFiles = new String[] { "DynusT.exe", "DLL_ramp.dll", "Ramp_Meter_Fixed_CDLL.dll", "Ramp_Meter_Feedback_CDLL.dll", "Ramp_Meter_Feedback_FDLL.dll", "libifcoremd.dll", "libmmd.dll", "Ramp_Meter_Fixed_FDLL.dll", "libiomp5md.dll" }; final String[] modelFiles = new String[] { "network.dat", "scenario.dat", "control.dat", "ramp.dat", "incident.dat", "movement.dat", "vms.dat", "origin.dat", "destination.dat", "StopCap4Way.dat", "StopCap2Way.dat", "YieldCap.dat", "WorkZone.dat", "GradeLengthPCE.dat", "leftcap.dat", "system.dat", "output_option.dat", "bg_demand_adjust.dat", "xy.dat", "TrafficFlowModel.dat", "parameter.dat" }; log.info("Creating iteration-directory..."); File iterDir = new File(this.tmpDir); if (!iterDir.exists()) { iterDir.mkdir(); } log.info("Copying application files to iteration-directory..."); for (String filename : exeFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.dynusTDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } log.info("Copying model files to iteration-directory..."); for (String filename : modelFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.modelDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } String logfileName = this.tmpDir + "/dynus-t.log"; String cmd = this.tmpDir + "/DynusT.exe"; log.info("running command: " + cmd); int timeout = 14400; int exitcode = ExeRunner.run(cmd, logfileName, timeout); if (exitcode != 0) { throw new RuntimeException("There was a problem running Dynus-T. exit code: " + exitcode); } }
11
Code Sample 1: @Override public RServiceResponse execute(final NexusServiceRequest inData) throws NexusServiceException { final RServiceRequest data = (RServiceRequest) inData; final RServiceResponse retval = new RServiceResponse(); final StringBuilder result = new StringBuilder("R service call results:\n"); RSession session; RConnection connection = null; try { result.append("Session Attachment: \n"); final byte[] sessionBytes = data.getSession(); if (sessionBytes != null && sessionBytes.length > 0) { session = RUtils.getInstance().bytesToSession(sessionBytes); result.append(" attaching to " + session + "\n"); connection = session.attach(); } else { result.append(" creating new session\n"); connection = new RConnection(data.getServerAddress()); } result.append("Input Parameters: \n"); for (String attributeName : data.getInputVariables().keySet()) { final Object parameter = data.getInputVariables().get(attributeName); if (parameter instanceof URI) { final FileObject file = VFS.getManager().resolveFile(((URI) parameter).toString()); final RFileOutputStream ros = connection.createFile(file.getName().getBaseName()); IOUtils.copy(file.getContent().getInputStream(), ros); connection.assign(attributeName, file.getName().getBaseName()); } else { connection.assign(attributeName, RUtils.getInstance().convertToREXP(parameter)); } result.append(" " + parameter.getClass().getSimpleName() + " " + attributeName + "=" + parameter + "\n"); } final REXP rExpression = connection.eval(RUtils.getInstance().wrapCode(data.getCode().replace('\r', '\n'))); result.append("Execution results:\n" + rExpression.asString() + "\n"); if (rExpression.isNull() || rExpression.asString().startsWith("Error")) { retval.setErr(rExpression.asString()); throw new NexusServiceException("R error: " + rExpression.asString()); } result.append("Output Parameters:\n"); final String[] rVariables = connection.eval("ls();").asStrings(); for (String varname : rVariables) { final String[] rVariable = connection.eval("class(" + varname + ")").asStrings(); if (rVariable.length == 2 && "file".equals(rVariable[0]) && "connection".equals(rVariable[1])) { final String rFileName = connection.eval("showConnections(TRUE)[" + varname + "]").asString(); result.append(" R File ").append(varname).append('=').append(rFileName).append('\n'); final RFileInputStream rInputStream = connection.openFile(rFileName); final File file = File.createTempFile("nexus-" + data.getRequestId(), ".dat"); IOUtils.copy(rInputStream, new FileOutputStream(file)); retval.getOutputVariables().put(varname, file.getCanonicalFile().toURI()); } else { final Object varvalue = RUtils.getInstance().convertREXP(connection.eval(varname)); retval.getOutputVariables().put(varname, varvalue); final String printValue = varvalue == null ? "null" : varvalue.getClass().isArray() ? Arrays.asList(varvalue).toString() : varvalue.toString(); result.append(" ").append(varvalue == null ? "" : varvalue.getClass().getSimpleName()).append(' ').append(varname).append('=').append(printValue).append('\n'); } } } catch (ClassNotFoundException cnfe) { retval.setErr(cnfe.getMessage()); LOGGER.error("Rserve Exception", cnfe); } catch (RserveException rse) { retval.setErr(rse.getMessage()); LOGGER.error("Rserve Exception", rse); } catch (REXPMismatchException rme) { retval.setErr(rme.getMessage()); LOGGER.error("REXP Mismatch Exception", rme); } catch (IOException rme) { retval.setErr(rme.getMessage()); LOGGER.error("IO Exception copying file ", rme); } finally { result.append("Session Detachment:\n"); if (connection != null) { RSession outSession; if (retval.isKeepSession()) { try { outSession = connection.detach(); } catch (RserveException e) { LOGGER.debug("Error detaching R session", e); outSession = null; } } else { outSession = null; } final boolean close = outSession == null; if (!close) { retval.setSession(RUtils.getInstance().sessionToBytes(outSession)); result.append(" suspended session for later use\n"); } connection.close(); retval.setSession(null); result.append(" session closed.\n"); } } retval.setOut(result.toString()); return retval; } Code Sample 2: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void doCopyFile(FileInputStream in, FileOutputStream out) { FileChannel inChannel = null, outChannel = null; try { inChannel = in.getChannel(); outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw ManagedIOException.manage(e); } finally { if (inChannel != null) { close(inChannel); } if (outChannel != null) { close(outChannel); } } }
11
Code Sample 1: public void unzip(String resource) { File f = new File(resource); if (!f.exists()) throw new RuntimeException("The specified resources does not exist (" + resource + ")"); String parent = f.getParent().toString(); try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(resource); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { log.info("Extracting archive entry: " + entry); String entryPath = new StringBuilder(parent).append(System.getProperty("file.separator")).append(entry.getName()).toString(); if (entry.isDirectory()) { log.info("Creating directory: " + entryPath); (new File(entryPath)).mkdir(); continue; } int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(entryPath); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(File source, File dest) throws Exception { log.warn("File names are " + source.toString() + " and " + dest.toString()); if (!dest.getParentFile().exists()) dest.getParentFile().mkdir(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } } Code Sample 2: protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
11
Code Sample 1: private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; } 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: public void render(final HttpServletRequest request, final HttpServletResponse response, InputStream inputStream, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } IOUtils.copy(inputStream, response.getOutputStream()); } 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 static void readIzvestiyaArticles() throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';'); reader.setTrimWhitespace(true); try { while (reader.readRecord()) { String id = reader.get(0); String filename = reader.get(1); StringTokenizer st = new StringTokenizer(filename, "-."); String name = st.nextToken(); String volume = st.nextToken(); String year = st.nextToken(); String extension = st.nextToken(); String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension); id2filename.put(id, filepath); } } finally { reader.close(); } for (Map.Entry<String, String> entry : id2filename.entrySet()) { String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue()); filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX"); if (new File(filepath).exists()) { InputStream in = new FileInputStream(filepath); FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false); try { org.apache.commons.io.IOUtils.copy(in, out); } catch (Exception e) { org.apache.commons.io.IOUtils.closeQuietly(in); org.apache.commons.io.IOUtils.closeQuietly(out); } } else { logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist"); } } } Code Sample 2: protected void setRankOrder() { this.rankOrder = new int[values.length]; for (int i = 0; i < rankOrder.length; i++) { rankOrder[i] = i; assert (!Double.isNaN(values[i])); } for (int i = rankOrder.length - 1; i >= 0; i--) { boolean swapped = false; for (int j = 0; j < i; j++) if (values[rankOrder[j]] < values[rankOrder[j + 1]]) { int r = rankOrder[j]; rankOrder[j] = rankOrder[j + 1]; rankOrder[j + 1] = r; } } }
11
Code Sample 1: public static String md5(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[FOUR_BYTES]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static String encryptString(String str) { StringBuffer sb = new StringBuffer(); int i; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); byte[] md5Bytes = md5.digest(); for (i = 0; i < md5Bytes.length; i++) { sb.append(md5Bytes[i]); } } catch (Exception e) { } return sb.toString(); }
00
Code Sample 1: public static byte[] getHashedPassword(String password, byte[] randomBytes) { byte[] hashedPassword = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(randomBytes); messageDigest.update(password.getBytes("UTF-8")); hashedPassword = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hashedPassword; } Code Sample 2: public DataSetInfo(String request) throws AddeURLException { URLConnection urlc; BufferedReader reader; debug = debug || request.indexOf("debug=true") >= 0; try { URL url = new URL(request); urlc = url.openConnection(); reader = new BufferedReader(new InputStreamReader(urlc.getInputStream())); } catch (AddeURLException ae) { status = -1; throw new AddeURLException("No datasets found"); } catch (Exception e) { status = -1; throw new AddeURLException("Error opening connection: " + e); } int numBytes = ((AddeURLConnection) urlc).getInitialRecordSize(); if (debug) System.out.println("DataSetInfo: numBytes = " + numBytes); if (numBytes == 0) { status = -1; throw new AddeURLException("No datasets found"); } else { data = new char[numBytes]; try { int start = 0; while (start < numBytes) { int numRead = reader.read(data, start, (numBytes - start)); if (debug) System.out.println("bytes read = " + numRead); start += numRead; } } catch (IOException e) { status = -1; throw new AddeURLException("Error reading dataset info:" + e); } int numNames = data.length / 80; descriptorTable = new Hashtable(numNames); if (debug) System.out.println("Number of descriptors = " + numNames); for (int i = 0; i < numNames; i++) { String temp = new String(data, i * 80, 80); if (debug) System.out.println("Parsing: >" + temp + "<"); if (temp.trim().equals("")) continue; String descriptor = temp.substring(0, 12).trim(); if (debug) System.out.println("Descriptor = " + descriptor); String comment = descriptor; int pos = temp.indexOf('"'); if (debug) System.out.println("Found quote at " + pos); if (pos >= 23) { comment = temp.substring(pos + 1).trim(); if (comment.equals("")) comment = descriptor; } if (debug) System.out.println("Comment = " + comment); descriptorTable.put(comment, descriptor); } } }
11
Code Sample 1: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } Code Sample 2: public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } }
00
Code Sample 1: @Override public User createUser(User bean) throws SitoolsException { checkUser(); if (!User.isValid(bean)) { throw new SitoolsException("CREATE_USER_MALFORMED"); } Connection cx = null; try { cx = ds.getConnection(); cx.setAutoCommit(false); PreparedStatement st = cx.prepareStatement(jdbcStoreResource.CREATE_USER); int i = 1; st.setString(i++, bean.getIdentifier()); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getSecret()); st.setString(i++, bean.getEmail()); st.executeUpdate(); st.close(); createProperties(bean, cx); if (!cx.getAutoCommit()) { cx.commit(); } } catch (SQLException e) { try { cx.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw new SitoolsException("CREATE_USER ROLLBACK" + e1.getMessage(), e1); } e.printStackTrace(); throw new SitoolsException("CREATE_USER " + e.getMessage(), e); } finally { closeConnection(cx); } return getUserById(bean.getIdentifier()); } Code Sample 2: private String digestMd5(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return "{MD5}" + base64; }
11
Code Sample 1: 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); } } } } } Code Sample 2: @Override public String fetchElectronicEdition(Publication pub) { final String url = baseURL + pub.getKey() + ".html"; logger.info("fetching pub ee from local cache at: " + url); HttpMethod method = null; String responseBody = ""; method = new GetMethod(url); method.setFollowRedirects(true); try { if (StringUtils.isNotBlank(method.getURI().getScheme())) { InputStream is = null; StringWriter writer = new StringWriter(); try { client.executeMethod(method); Header contentType = method.getResponseHeader("Content-Type"); if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) { is = method.getResponseBodyAsStream(); IOUtils.copy(is, writer); responseBody = writer.toString(); } else { logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType); } } catch (HttpException he) { logger.error("Http error connecting to '" + url + "'"); logger.error(he.getMessage()); } catch (IOException ioe) { logger.error("Unable to connect to '" + url + "'"); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(writer); } } } catch (URIException e) { logger.error(e); } finally { method.releaseConnection(); } return responseBody; }
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: protected ResourceBundle loadBundle(String prefix) { URL url = Thread.currentThread().getContextClassLoader().getResource(prefix + ".properties"); if (url != null) { try { return new PropertyResourceBundle(url.openStream()); } catch (IOException e) { throw ThrowableManagerRegistry.caught(e); } } return null; }
00
Code Sample 1: private SystemProperties() { Properties p = new Properties(); ClassLoader classLoader = getClass().getClassLoader(); try { URL url = classLoader.getResource("system.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } try { URL url = classLoader.getResource("system-ext.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } boolean systemPropertiesLoad = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_LOAD), true); boolean systemPropertiesFinal = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_FINAL), true); if (systemPropertiesLoad) { Enumeration enu = p.propertyNames(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); if (systemPropertiesFinal || Validator.isNull(System.getProperty(key))) { System.setProperty(key, (String) p.get(key)); } } } PropertiesUtil.fromProperties(p, _props); } Code Sample 2: private String md5(String txt) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(txt.getBytes(), 0, txt.length()); return new BigInteger(1, m.digest()).toString(16); } catch (Exception e) { return "BAD MD5"; } }
00
Code Sample 1: private String createHash() { String hash = ""; try { final java.util.Calendar c = java.util.Calendar.getInstance(); String day = "" + c.get(java.util.Calendar.DATE); day = (day.length() == 1) ? '0' + day : day; String month = "" + (c.get(java.util.Calendar.MONTH) + 1); month = (month.length() == 1) ? '0' + month : month; final String hashString = getStringProperty("hashkey") + day + "." + month + "." + c.get(java.util.Calendar.YEAR); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(hashString.getBytes()); final byte digest[] = md.digest(); hash = ""; for (int i = 0; i < digest.length; i++) { final String s = Integer.toHexString(digest[i] & 0xFF); hash += ((s.length() == 1) ? "0" + s : s); } } catch (final NoSuchAlgorithmException e) { bot.getLogger().log(e); } return hash; } Code Sample 2: private void handleInterfaceReparented(String ipAddr, Parms eventParms) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (log.isDebugEnabled()) log.debug("interfaceReparented event received..."); if (ipAddr == null || eventParms == null) { log.warn(EventConstants.INTERFACE_REPARENTED_EVENT_UEI + " ignored - info incomplete - ip/parms: " + ipAddr + "/" + eventParms); return; } long oldNodeId = -1; long newNodeId = -1; String parmName = null; Value parmValue = null; String parmContent = null; Enumeration parmEnum = eventParms.enumerateParm(); while (parmEnum.hasMoreElements()) { Parm parm = (Parm) parmEnum.nextElement(); parmName = parm.getParmName(); parmValue = parm.getValue(); if (parmValue == null) continue; else parmContent = parmValue.getContent(); if (parmName.equals(EventConstants.PARM_OLD_NODEID)) { try { oldNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_OLD_NODEID + " cannot be non-numeric"); oldNodeId = -1; } } else if (parmName.equals(EventConstants.PARM_NEW_NODEID)) { try { newNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_NEW_NODEID + " cannot be non-numeric"); newNodeId = -1; } } } if (newNodeId == -1 || oldNodeId == -1) { log.warn("Unable to process 'interfaceReparented' event, invalid event parm."); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement reparentOutagesStmt = dbConn.prepareStatement(OutageConstants.DB_REPARENT_OUTAGES); reparentOutagesStmt.setLong(1, newNodeId); reparentOutagesStmt.setLong(2, oldNodeId); reparentOutagesStmt.setString(3, ipAddr); int count = reparentOutagesStmt.executeUpdate(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Reparented " + count + " outages - ip: " + ipAddr + " reparented from " + oldNodeId + " to " + newNodeId); } catch (SQLException se) { log.warn("Rolling back transaction, reparent outages failed for newNodeId/ipAddr: " + newNodeId + "/" + ipAddr); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } reparentOutagesStmt.close(); } catch (SQLException se) { log.warn("SQL exception while handling \'interfaceReparented\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: private Document getXMLDoc(Region region) { Document doc; try { InputStream stream; URL url = new URL("http://eve-central.com/api/marketstat?hours=" + HOURS + "&" + getTypes() + "&regionlimit=" + region.getTypeID()); System.out.println(url.toString()); stream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); doc = parser.parse(stream); } catch (MalformedURLException e) { e.printStackTrace(); doc = new DefaultDocument(); } catch (SAXException e) { e.printStackTrace(); doc = new DefaultDocument(); } catch (IOException e) { e.printStackTrace(); doc = new DefaultDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); doc = new DefaultDocument(); } return doc; } Code Sample 2: public DownloadThread call() throws UpdateModException { try { Thread.currentThread().setName("Download - " + modName); if (url != null) { URL urls = new URL(this.url); URLConnection connection = urls.openConnection(); connection.setConnectTimeout(7500); InputStream is = urls.openStream(); String filename = null; if (path == null || path.isEmpty()) { String pattern = "[^a-z,A-Z,0-9, ,.]"; filename = this.url.substring(this.url.lastIndexOf("/") + 1).replace("%20", " "); filename = filename.replaceAll(pattern, ""); } else { filename = path; } FileOutputStream fos = null; file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename); fos = new FileOutputStream(file, false); FileUtils.copyInputStream(is, fos); is.close(); fos.flush(); fos.close(); } } catch (MalformedURLException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (ConnectException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (NullPointerException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (InvalidParameterException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (FileNotFoundException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (IOException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } return this; }
00
Code Sample 1: static Object loadPersistentRepresentationFromFile(URL url) throws PersistenceException { PersistenceManager.persistenceURL.get().addFirst(url); ObjectInputStream ois = null; HierarchicalStreamReader reader = null; XStream xstream = null; try { Reader inputReader = new java.io.InputStreamReader(url.openStream()); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader xsr = inputFactory.createXMLStreamReader(url.toExternalForm(), inputReader); reader = new StaxReader(new QNameMap(), xsr); } catch (XMLStreamException xse) { throw new PersistenceException("Error creating reader", xse); } xstream = new XStream(new StaxDriver()); xstream.setClassLoader(Gate.getClassLoader()); ois = xstream.createObjectInputStream(reader); Object res = null; Iterator urlIter = ((Collection) PersistenceManager.getTransientRepresentation(ois.readObject())).iterator(); while (urlIter.hasNext()) { URL anUrl = (URL) urlIter.next(); try { Gate.getCreoleRegister().registerDirectories(anUrl); } catch (GateException ge) { Err.prln("Could not reload creole directory " + anUrl.toExternalForm()); } } res = ois.readObject(); ois.close(); return res; } catch (PersistenceException pe) { throw pe; } catch (Exception e) { throw new PersistenceException("Error loading GAPP file", e); } finally { PersistenceManager.persistenceURL.get().removeFirst(); if (PersistenceManager.persistenceURL.get().isEmpty()) { PersistenceManager.persistenceURL.remove(); } } } Code Sample 2: protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); }
11
Code Sample 1: public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } } Code Sample 2: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } }
11
Code Sample 1: public static String getHash(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(password.getBytes()); return new String(digest.digest()); } catch (NoSuchAlgorithmException e) { log.error("Hashing algorithm not found"); return password; } } Code Sample 2: protected final String H(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(data.getBytes("UTF8")); byte[] bytes = digest.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { int aByte = bytes[i]; if (aByte < 0) aByte += 256; if (aByte < 16) sb.append('0'); sb.append(Integer.toHexString(aByte)); } return sb.toString(); }
00
Code Sample 1: public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } } Code Sample 2: public void testDecodeJTLM_publish100() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.DEFAULT_OPTIONS); String[] exiFiles = { "/JTLM/publish100/publish100.bitPacked", "/JTLM/publish100/publish100.byteAligned", "/JTLM/publish100/publish100.preCompress", "/JTLM/publish100/publish100.compress" }; for (int i = 0; i < Alignments.length; i++) { AlignmentType alignment = Alignments[i]; EXIDecoder decoder = new EXIDecoder(); Scanner scanner; decoder.setAlignmentType(alignment); URL url = resolveSystemIdAsURL(exiFiles[i]); int n_events, n_texts; decoder.setEXISchema(grammarCache); decoder.setInputStream(url.openStream()); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { String stringValue = exiEvent.getCharacters().makeString(); if (stringValue.length() == 0 && exiEvent.getEventType().itemType == EventCode.ITEM_SCHEMA_CH) { --n_events; continue; } if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(publish100_centennials[n], stringValue); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(10610, n_events); } }
11
Code Sample 1: public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; } Code Sample 2: private static void updateLeapSeconds() throws IOException, MalformedURLException, NumberFormatException { URL url = new URL("http://cdf.gsfc.nasa.gov/html/CDFLeapSeconds.txt"); InputStream in; try { in = url.openStream(); } catch (IOException ex) { url = LeapSecondsConverter.class.getResource("CDFLeapSeconds.txt"); in = url.openStream(); System.err.println("Using local copy of leap seconds!!!"); } BufferedReader r = new BufferedReader(new InputStreamReader(in)); String s = ""; leapSeconds = new ArrayList(50); withoutLeapSeconds = new ArrayList(50); String lastLine = s; while (s != null) { s = r.readLine(); if (s == null) { System.err.println("Last leap second read from " + url + " " + lastLine); continue; } if (s.startsWith(";")) { continue; } String[] ss = s.trim().split("\\s+", -2); if (ss[0].compareTo("1972") < 0) { continue; } int iyear = Integer.parseInt(ss[0]); int imonth = Integer.parseInt(ss[1]); int iday = Integer.parseInt(ss[2]); int ileap = (int) (Double.parseDouble(ss[3])); double us2000 = TimeUtil.createTimeDatum(iyear, imonth, iday, 0, 0, 0, 0).doubleValue(Units.us2000); leapSeconds.add(Long.valueOf(((long) us2000) * 1000L - 43200000000000L + (long) (ileap - 32) * 1000000000)); withoutLeapSeconds.add(us2000); } leapSeconds.add(Long.MAX_VALUE); withoutLeapSeconds.add(Double.MAX_VALUE); lastUpdateMillis = System.currentTimeMillis(); }
11
Code Sample 1: @Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } } Code Sample 2: public static void copy(String source, String destination) { FileReader in = null; FileWriter out = null; try { File inputFile = new File(source); File outputFile = new File(destination); in = new FileReader(inputFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("i") != null) { String img = req.getParameter("i"); if (img == null) { resp.sendError(404, "Image was null"); return; } File f = null; if (img.startsWith("file")) { try { f = new File(new URI(img)); } catch (URISyntaxException e) { resp.sendError(500, e.getMessage()); return; } } else { f = new File(img); } if (f.exists()) { f = f.getCanonicalFile(); if (f.getName().endsWith(".jpg") || f.getName().endsWith(".png")) { resp.setContentType("image/png"); FileInputStream fis = null; OutputStream os = resp.getOutputStream(); try { fis = new FileInputStream(f); IOUtils.copy(fis, os); } finally { os.flush(); if (fis != null) fis.close(); } } } return; } String mediaUrl = "/media" + req.getPathInfo(); String parts[] = mediaUrl.split("/"); mediaHandler.handleRequest(parts, req, resp); } Code Sample 2: private String postData(String requestUrl, String atom) throws AuthenticationException, IOException { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String header; try { header = oauthAuthenticator.getHttpAuthorizationHeader(url.toString(), "POST", profile.getOAuthToken(), profile.getOAuthTokenSecret()); } catch (OAuthException e) { throw new AuthenticationException(e); } conn.setRequestProperty("Authorization", header); conn.setRequestProperty("Content-Type", "application/atom+xml"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); writer.write(atom); writer.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(); } InputStreamReader reader = new InputStreamReader(conn.getInputStream()); char[] buffer = new char[1024]; int bytesRead = 0; StringBuilder data = new StringBuilder(); while ((bytesRead = reader.read(buffer)) != -1) { data.append(buffer, 0, bytesRead); } reader.close(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + data); } return data.toString(); }
00
Code Sample 1: void copyTo(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { if (shouldMock()) { return; } assert httpRequest != null; assert httpResponse != null; final long start = System.currentTimeMillis(); try { final URLConnection connection = openConnection(url, headers); connection.setRequestProperty("Accept-Language", httpRequest.getHeader("Accept-Language")); connection.connect(); try { InputStream input = connection.getInputStream(); if ("gzip".equals(connection.getContentEncoding())) { input = new GZIPInputStream(input); } httpResponse.setContentType(connection.getContentType()); TransportFormat.pump(input, httpResponse.getOutputStream()); } finally { close(connection); } } finally { LOGGER.info("http call done in " + (System.currentTimeMillis() - start) + " ms for " + url); } } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; }
00
Code Sample 1: public IntactOntology parseOboFile(URL url, boolean keepTemporaryFile) throws PsiLoaderException { if (url == null) { throw new IllegalArgumentException("Please give a non null URL."); } StringBuffer buffer = new StringBuffer(1024 * 8); try { System.out.println("Loading URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()), 1024); String line; int lineCount = 0; while ((line = in.readLine()) != null) { lineCount++; buffer.append(line).append(NEW_LINE); if ((lineCount % 20) == 0) { System.out.print("."); System.out.flush(); if ((lineCount % 500) == 0) { System.out.println(" " + lineCount); } } } in.close(); File tempDirectory = new File(System.getProperty("java.io.tmpdir", "tmp")); if (!tempDirectory.exists()) { if (!tempDirectory.mkdirs()) { throw new IOException("Cannot create temp directory: " + tempDirectory.getAbsolutePath()); } } System.out.println("Using temp directory: " + tempDirectory.getAbsolutePath()); File tempFile = File.createTempFile("psimi.v25.", ".obo", tempDirectory); tempFile.deleteOnExit(); tempFile.deleteOnExit(); System.out.println("The OBO file is temporary store as: " + tempFile.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(tempFile), 1024); out.write(buffer.toString()); out.flush(); out.close(); return parseOboFile(tempFile); } catch (IOException e) { throw new PsiLoaderException("Error while loading URL (" + url + ")", e); } } Code Sample 2: public static final void copy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; 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"); } }
11
Code Sample 1: private String generateFilename() { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); try { digest.update(InetAddress.getLocalHost().toString().getBytes()); } catch (UnknownHostException e) { } digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(Runtime.getRuntime().freeMemory()).getBytes()); byte[] foo = new byte[128]; new SecureRandom().nextBytes(foo); digest.update(foo); hash = digest.digest(); } catch (NoSuchAlgorithmException e) { Debug.assrt(false); } return hexEncode(hash); } Code Sample 2: public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); }
00
Code Sample 1: public static OutputStream getOutputStream(String path) throws ResourceException { URL url = getURL(path); if (url != null) { try { return url.openConnection().getOutputStream(); } catch (IOException e) { throw new ResourceException(e); } } else { throw new ResourceException("Error obtaining resource, invalid path: " + path); } } Code Sample 2: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
00
Code Sample 1: protected URLConnection openURLConnection() throws IOException { final String locator = getMediaLocator(); if (locator == null) { return null; } final URL url; try { url = new URL(locator); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } final URLConnection connection = url.openConnection(); connection.connect(); return connection; } Code Sample 2: private synchronized void configure() { final Map res = new HashMap(); try { final Enumeration resources = getConfigResources(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); while (resources.hasMoreElements()) { final URL url = (URL) resources.nextElement(); DefaultHandler saxHandler = new DefaultHandler() { private Group group; private StringBuffer tagContent = new StringBuffer(); public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("group".equals(qName)) { group = new Group(attributes.getValue("name")); String minimizeJs = attributes.getValue("minimize"); String minimizeCss = attributes.getValue("minimizeCss"); group.setMinimize(!"false".equals(minimizeJs)); group.setMinimizeCss("true".equals(minimizeCss)); } else if ("js".equals(qName) || "css".equals(qName) || "group-ref".equals(qName)) tagContent.setLength(0); } public void characters(char ch[], int start, int length) throws SAXException { tagContent.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { if ("group".equals(qName)) res.put(group.getName(), group); else if ("js".equals(qName)) group.getJsNames().add(tagContent.toString()); else if ("css".equals(qName)) group.getCssNames().add(tagContent.toString()); else if ("group-ref".equals(qName)) { String name = tagContent.toString(); Group subGroup = (Group) res.get(name); if (subGroup == null) throw new RuntimeException("Error parsing " + url.toString() + " <group-ref>" + name + "</group-ref> unknown"); group.getSubgroups().add(subGroup); } } }; try { saxParser.parse(url.openStream(), saxHandler); } catch (Throwable e) { log.warn(e.toString(), e); log.warn("Exception " + e.toString() + " ignored, let's move on.."); } } configurationFilesMaxModificationTime = findMaxConfigModificationTime(); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } this.groups = res; }
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: public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
00
Code Sample 1: public static void testString(String string, String expected) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(string.getBytes(), 0, string.length()); String result = toString(md.digest()); System.out.println(expected); System.out.println(result); if (!expected.equals(result)) System.out.println("NOT EQUAL!"); } catch (Exception x) { x.printStackTrace(); } } Code Sample 2: public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
11
Code Sample 1: public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); } Code Sample 2: public 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 Metadata readMetadataIndexFileFromNetwork(String mediaMetadataURI) throws IOException { Metadata tempMetadata = new Metadata(); URL url = new URL(mediaMetadataURI); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String tempLine = null; while ((tempLine = input.readLine()) != null) { Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine); if (tempProperty != null) { tempMetadata.addIfNotNull(tempProperty.getKey(), tempProperty.getValue()); } } input.close(); return tempMetadata; } Code Sample 2: public byte[] getHash(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes("UTF-8")); return digest.digest(plaintext.getBytes("UTF-8")); }
00
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 static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
00
Code Sample 1: public static void BubbleSortLong2(long[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { long temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); } Code Sample 2: public Project createProject(int testbedID, String name, String description) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO Projects(testbedID, name, " + "description) VALUES (" + testbedID + ", '" + name + "', '" + description + "')"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM Projects WHERE " + " testbedID = " + testbedID + " AND " + " name = '" + name + "' AND " + " description = '" + description + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; }
00
Code Sample 1: private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); InputStream is = vds.getContentStream(); IOUtils.copy(is, m_zout); is.close(); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } } Code Sample 2: public String getHTTPContent(String sUrl, String encode, String cookie, String host, String referer) { HttpURLConnection connection = null; InputStream in = null; StringBuffer strResult = new StringBuffer(); try { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); if (!isStringNull(host)) this.setHttpInfo(connection, cookie, host, referer); connection.connect(); int httpStatus = connection.getResponseCode(); if (httpStatus != 200) log.info("getHTTPConent error httpStatus - " + httpStatus); in = new BufferedInputStream(connection.getInputStream()); String inputLine = null; byte[] b = new byte[40960]; int len = 0; while ((len = in.read(b)) > 0) { inputLine = new String(b, 0, len, encode); strResult.append(inputLine.replaceAll("[\t\n\r ]", " ")); } in.close(); } catch (IOException e) { log.warn("SpiderUtil getHTTPConent IOException -> ", e); } finally { if (in != null) try { in.close(); } catch (IOException e) { } } return strResult.toString(); }
11
Code Sample 1: public static void copy(final File src, final File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); } Code Sample 2: private static void copyFile(String src, String dest) throws IOException { File destFile = new File(dest); if (destFile.exists()) { destFile.delete(); } FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } }
00
Code Sample 1: private boolean hasPackageInfo(URL url) { if (url == null) return false; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { if (line.startsWith("Specification-Title: ") || line.startsWith("Specification-Version: ") || line.startsWith("Specification-Vendor: ") || line.startsWith("Implementation-Title: ") || line.startsWith("Implementation-Version: ") || line.startsWith("Implementation-Vendor: ")) return true; } } catch (IOException ioe) { } finally { if (br != null) try { br.close(); } catch (IOException e) { } } return false; } Code Sample 2: @Override public long insertStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); long result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return getInsertId(statement); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
11
Code Sample 1: public static void copyFile(File source, File destination) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[4096]; int read = -1; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.flush(); out.close(); in.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static List<String> readListFile(URL url) { List<String> names = new ArrayList<String>(); if (url != null) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { names.add(line); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } } } return names; } Code Sample 2: private void readVersion() { URL url = ClassLoader.getSystemResource("version"); if (url == null) { return; } BufferedReader reader = null; String line = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { if (line.startsWith("Version=")) { version = (line.split("="))[1]; } if (line.startsWith("Revision=")) { revision = (line.split("="))[1]; } if (line.startsWith("Date=")) { String sSec = (line.split("="))[1]; Long lSec = Long.valueOf(sSec); compileDate = new Date(lSec); } } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void proxyRequest(IPageContext context, Writer writer, String proxyPath) throws IOException { URLConnection connection = new URL(proxyPath).openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "text/html; charset=UTF-8"); connection.setReadTimeout(30000); connection.setConnectTimeout(5000); Enumeration<String> e = context.httpRequest().getHeaderNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (name.equalsIgnoreCase("HOST") || name.equalsIgnoreCase("Accept-Encoding") || name.equalsIgnoreCase("Authorization")) continue; Enumeration<String> headers = context.httpRequest().getHeaders(name); while (headers.hasMoreElements()) { String header = headers.nextElement(); connection.setRequestProperty(name, header); } } if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod(context.httpRequest().getMethod()); if ("POST".equalsIgnoreCase(context.httpRequest().getMethod()) || "PUT".equalsIgnoreCase(context.httpRequest().getMethod())) { Enumeration<String> names = context.httpRequest().getParameterNames(); StringBuilder body = new StringBuilder(); while (names.hasMoreElements()) { String key = names.nextElement(); for (String value : context.parameters(key)) { if (body.length() > 0) { body.append('&'); } try { body.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException ex) { } } } if (body.length() > 0) { connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(body.toString()); out.close(); } } } try { IOUtils.copy(connection.getInputStream(), writer); } catch (IOException ex) { writer.write("<span>SSI Error: " + ex.getMessage() + "</span>"); } }
00
Code Sample 1: public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; } Code Sample 2: public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); }
11
Code Sample 1: public boolean moveFileSafely(final File in, final File out) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; final File tempOut = File.createTempFile("move", ".tmp"); try { fis = new FileInputStream(in); fos = new FileOutputStream(tempOut); inChannel = fis.getChannel(); outChannel = fos.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel); } try { if (fis != null) fis.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis); } try { if (fos != null) fos.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos); } } out.delete(); if (!out.exists()) { tempOut.renameTo(out); return in.delete(); } return false; } Code Sample 2: public void saveToPackage() { boolean inPackage = false; String className = IconEditor.className; if (!checkPackage()) { JOptionPane.showMessageDialog(this, "No package selected. Aborting.", "Package not selected!", JOptionPane.WARNING_MESSAGE); return; } File iconFile = new File(getPackageFile().getParent() + File.separator + classIcon); File prevIconFile = new File(prevPackagePath + File.separator + classIcon); if ((IconEditor.getClassIcon() == null) || !prevIconFile.exists()) { IconEditor.setClassIcon("default.gif"); } else if (prevIconFile.exists() && (prevIconFile.compareTo(iconFile) != 0)) { FileFuncs.copyImageFile(prevIconFile, iconFile); } ci = new ClassImport(getPackageFile(), packageClassNamesList, packageClassList); for (int i = 0; i < packageClassList.size(); i++) { if (IconEditor.className.equalsIgnoreCase(packageClassList.get(i).getName())) { inPackage = true; classX = 0 - classX; classY = 0 - classY; shapeList.shift(classX, classY); packageClassList.get(i).setBoundingbox(boundingbox); packageClassList.get(i).setDescription(IconEditor.classDescription); if (IconEditor.getClassIcon() == null) { packageClassList.get(i).setIconName("default.gif"); } else { packageClassList.get(i).setIconName(IconEditor.getClassIcon()); } packageClassList.get(i).setIsRelation(IconEditor.classIsRelation); packageClassList.get(i).setName(IconEditor.className); packageClassList.get(i).setPorts(ports); packageClassList.get(i).shiftPorts(classX, classY); packageClassList.get(i).setShapeList(shapeList); if (dbrClassFields != null && dbrClassFields.getRowCount() > 0) { fields.clear(); for (int j = 0; j < dbrClassFields.getRowCount(); j++) { String fieldName = dbrClassFields.getValueAt(j, iNAME); String fieldType = dbrClassFields.getValueAt(j, iTYPE); String fieldValue = dbrClassFields.getValueAt(j, iVALUE); ClassField field = new ClassField(fieldName, fieldType, fieldValue); fields.add(field); } } packageClassList.get(i).setFields(fields); packageClassList.add(packageClassList.get(i)); packageClassList.remove(i); break; } } try { BufferedReader in = new BufferedReader(new FileReader(getPackageFile())); String str; StringBuffer content = new StringBuffer(); while ((str = in.readLine()) != null) { if (inPackage && str.trim().startsWith("<class")) { break; } else if (!inPackage) { if (str.equalsIgnoreCase("</package>")) break; content.append(str + "\n"); } else if (inPackage) content.append(str + "\n"); } if (!inPackage) { content.append(getShapesInXML(false)); } else { for (int i = 0; i < packageClassList.size(); i++) { classX = 0; classY = 0; makeClass(packageClassList.get(i)); content.append(getShapesInXML(false)); } } content.append("</package>"); in.close(); File javaFile = new File(getPackageFile().getParent() + File.separator + className + ".java"); File prevJavaFile = new File(prevPackagePath + File.separator + className + ".java"); int overwriteFile = JOptionPane.YES_OPTION; if (javaFile.exists()) { overwriteFile = JOptionPane.showConfirmDialog(null, "Java class already exists. Overwrite?"); } if (overwriteFile != JOptionPane.CANCEL_OPTION) { FileOutputStream out = new FileOutputStream(new File(getPackageFile().getAbsolutePath())); out.write(content.toString().getBytes()); out.flush(); out.close(); if (overwriteFile == JOptionPane.YES_OPTION) { String fileText = null; if (prevJavaFile.exists()) { fileText = FileFuncs.getFileContents(prevJavaFile); } else { fileText = "class " + className + " {"; fileText += "\n /*@ specification " + className + " {\n"; for (int i = 0; i < dbrClassFields.getRowCount(); i++) { String fieldName = dbrClassFields.getValueAt(i, iNAME); String fieldType = dbrClassFields.getValueAt(i, iTYPE); if (fieldType != null) { fileText += " " + fieldType + " " + fieldName + ";\n"; } } fileText += " }@*/\n \n}"; } FileFuncs.writeFile(javaFile, fileText); } JOptionPane.showMessageDialog(null, "Saved to package: " + getPackageFile().getName(), "Saved", JOptionPane.INFORMATION_MESSAGE); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File sourceFile, File targetFile) throws FileCopyingException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileCopyingException(exceptionMessage, ioException); } } Code Sample 2: public 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(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } }
00
Code Sample 1: public int add(WebService ws) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into WebServices (MethodName, ServiceURI) " + "values ('" + ws.getMethodName() + "', '" + ws.getServiceURI() + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); int id; sql = "select currval('webservices_webserviceid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); PreparedStatement pstmt = conn.prepareStatement("insert into WebServiceParams " + "(WebServiceId, Position, ParameterName, Type) " + "values (?, ?, ?, ?)"); pstmt.setInt(1, id); pstmt.setInt(2, 0); pstmt.setString(3, null); pstmt.setInt(4, ws.getReturnType()); pstmt.executeUpdate(); for (Iterator it = ws.parametersIterator(); it.hasNext(); ) { WebServiceParameter param = (WebServiceParameter) it.next(); pstmt.setInt(2, param.getPosition()); pstmt.setString(3, param.getName()); pstmt.setInt(4, param.getType()); pstmt.executeUpdate(); } 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) { e.printStackTrace(); throw new FidoDatabaseException(e); } } Code Sample 2: Object execute(String method, Vector params) throws XmlRpcException, IOException { fault = false; long now = 0; if (XmlRpc.debug) { System.err.println("Client calling procedure '" + method + "' with parameters " + params); now = System.currentTimeMillis(); } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); if (buffer == null) { buffer = new ByteArrayOutputStream(); } else { buffer.reset(); } XmlWriter writer = new XmlWriter(buffer); writeRequest(writer, method, params); writer.flush(); byte[] request = buffer.toByteArray(); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); if (auth != null) { con.setRequestProperty("Authorization", "Basic " + auth); } OutputStream out = con.getOutputStream(); out.write(request); out.flush(); out.close(); InputStream in = con.getInputStream(); parse(in); } catch (Exception x) { if (XmlRpc.debug) { x.printStackTrace(); } throw new IOException(x.getMessage()); } if (fault) { XmlRpcException exception = null; try { Hashtable f = (Hashtable) result; String faultString = (String) f.get("faultString"); int faultCode = Integer.parseInt(f.get("faultCode").toString()); exception = new XmlRpcException(faultCode, faultString.trim()); } catch (Exception x) { throw new XmlRpcException(0, "Invalid fault response"); } throw exception; } if (XmlRpc.debug) { System.err.println("Spent " + (System.currentTimeMillis() - now) + " in request"); } return result; }
00
Code Sample 1: public final void build() { if (!built_) { built_ = true; final boolean[] done = new boolean[] { false }; Runnable runnable = new Runnable() { public void run() { try { exists_ = true; URL url = getContentURL(); URLConnection cnx = url.openConnection(); cnx.connect(); lastModified_ = cnx.getLastModified(); length_ = cnx.getContentLength(); type_ = cnx.getContentType(); if (isDirectory()) { InputStream in = cnx.getInputStream(); BufferedReader nr = new BufferedReader(new InputStreamReader(in)); FuVectorString v = readList(nr); nr.close(); v.sort(); v.uniq(); list_ = v.toArray(); } } catch (Exception ex) { exists_ = false; } done[0] = true; } }; Thread t = new Thread(runnable, "VfsFileUrl connection " + getContentURL()); t.setPriority(Math.max(Thread.MIN_PRIORITY, t.getPriority() - 1)); t.start(); for (int i = 0; i < 100; i++) { if (done[0]) break; try { Thread.sleep(300L); } catch (InterruptedException ex) { } } if (!done[0]) { t.interrupt(); exists_ = false; canRead_ = false; FuLog.warning("VFS: fail to get " + url_); } } } Code Sample 2: public synchronized String encrypt(String plaintext) { if (plaintext == null || plaintext.equals("")) { return plaintext; } String hash = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); hash = Base64.encodeBase64String(raw).replaceAll("\r\n", ""); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage()); } return hash; }
00
Code Sample 1: public int readRaw(byte[] buffer, int offset, int length) throws IOException { if (offset < 0 || length < 0 || (offset + length) > buffer.length) { throw new IndexOutOfBoundsException(); } HttpURLConnection connection = null; InputStream is = null; int n = 0; try { connection = (HttpURLConnection) url.openConnection(); String byteRange = "bytes=" + position + "-" + (position + length - 1); connection.setRequestProperty("Range", byteRange); is = connection.getInputStream(); while (n < length) { int count = is.read(buffer, offset + n, length - n); if (count < 0) { throw new EOFException(); } n += count; } position += n; return n; } catch (EOFException e) { return n; } catch (IOException e) { e.printStackTrace(); System.out.println("We're screwed..."); System.out.println(n); if (e.getMessage().contains("response code: 416")) { System.out.println("Trying to be mister nice guy, returning " + n); return n; } else { throw e; } } finally { if (is != null) { is.close(); } if (connection != null) { connection.disconnect(); } } } Code Sample 2: private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException { Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>(); Enumeration providerFiles = classLoader.getResources(resource); if (!providerFiles.hasMoreElements()) { logger.warning("Can't find the resource: " + resource); return pluginClasses; } do { URL url = (URL) providerFiles.nextElement(); InputStream stream = url.openStream(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { continue; } String line; while ((line = reader.readLine()) != null) { int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } line = line.trim(); if (line.length() > 0) { Class pluginClass; try { pluginClass = classLoader.loadClass(line); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e); continue; } if (Plugin.class.isAssignableFrom(pluginClass)) { pluginClasses.add((Class<? extends Plugin>) pluginClass); } else { logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin."); } } } reader.close(); stream.close(); } while (providerFiles.hasMoreElements()); return pluginClasses; }
11
Code Sample 1: @Test public void test20_badSmtp() throws Exception { Db db = DbConnection.defaultCieDbRW(); try { db.begin(); oldSmtp = Config.getProperty(db, "com.entelience.mail.MailHelper.hostName", "localhost"); oldSupport = Config.getProperty(db, "com.entelience.esis.feature.SupportNotifier", false); Config.setProperty(db, "com.entelience.mail.MailHelper.hostName", "127.0.10.1", 1); Config.setProperty(db, "com.entelience.esis.feature.SupportNotifier", "true", 1); PreparedStatement pst = db.prepareStatement("DELETE FROM t_client_errors"); db.executeUpdate(pst); db.commit(); } catch (Exception e) { db.rollback(); } finally { db.safeClose(); } } Code Sample 2: protected synchronized Long putModel(String table, String linkTable, String type, TupleBinding binding, LocatableModel model) { try { if (model.getId() != null && !"".equals(model.getId())) { ps7.setInt(1, Integer.parseInt(model.getId())); ps7.execute(); ps6.setInt(1, Integer.parseInt(model.getId())); ps6.execute(); } if (persistenceMethod == PostgreSQLStore.BYTEA) { ps1.setString(1, model.getContig()); ps1.setInt(2, model.getStartPosition()); ps1.setInt(3, model.getStopPosition()); ps1.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); ps1.setBytes(5, objData.getData()); ps1.executeUpdate(); } else if (persistenceMethod == PostgreSQLStore.OID || persistenceMethod == PostgreSQLStore.FIELDS) { ps1b.setString(1, model.getContig()); ps1b.setInt(2, model.getStartPosition()); ps1b.setInt(3, model.getStopPosition()); ps1b.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE); obj.write(objData.getData()); obj.close(); ps1b.setInt(5, oid); ps1b.executeUpdate(); } ResultSet rs = null; PreparedStatement ps = conn.prepareStatement("select currval('" + table + "_" + table + "_id_seq')"); rs = ps.executeQuery(); int modelId = -1; if (rs != null) { if (rs.next()) { modelId = rs.getInt(1); } } rs.close(); ps.close(); for (String key : model.getTags().keySet()) { int tagId = -1; if (tags.get(key) != null) { tagId = tags.get(key); } else { ps2.setString(1, key); rs = ps2.executeQuery(); if (rs != null) { while (rs.next()) { tagId = rs.getInt(1); } } rs.close(); } if (tagId < 0) { ps3.setString(1, key); ps3.setString(2, model.getTags().get(key)); ps3.executeUpdate(); rs = ps4.executeQuery(); if (rs != null) { if (rs.next()) { tagId = rs.getInt(1); tags.put(key, tagId); } } rs.close(); } ps5.setInt(1, tagId); ps5.executeUpdate(); } conn.commit(); return (new Long(modelId)); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } return (null); }
00
Code Sample 1: public static DBData resolveDBasURL(java.net.URL url) throws Exception { DBData data = null; InputStream fi = null; EnhancedStreamTokenizer tokenizer = null; try { fi = url.openStream(); tokenizer = new EnhancedStreamTokenizer(new BufferedReader(new InputStreamReader(fi))); initializeTokenizer(tokenizer); } catch (Exception e) { Console.getInstance().println("\nError occured while opening URL '" + url.toString() + "'"); Console.getInstance().println(e); return null; } if (tokenizer != null) { try { } finally { System.gc(); } } return data; } Code Sample 2: public static InputStream gunzip(final InputStream inputStream) throws IOException { Assert.notNull(inputStream, "inputStream"); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); InputOutputStream inputOutputStream = new InputOutputStream(); IOUtils.copy(gzipInputStream, inputOutputStream); return inputOutputStream.getInputStream(); }
00
Code Sample 1: public static void Sample2(String myField, String condition1, String condition2) throws SQLException { Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost/test", "user", "password"); connection.setAutoCommit(false); Statement st = connection.createStatement(); String sql = "UPDATE myTable SET myField = '" + myField + "' WHERE myOtherField1 = '" + condition1 + "' AND myOtherField2 = '" + condition2 + "'"; int numChanged = st.executeUpdate(sql); // If more than 10 entries change, panic and rollback if(numChanged > 10) { connection.rollback(); } else { connection.commit(); } st.close(); connection.close(); } Code Sample 2: public Image getURLImage(String url) { if (!images.containsKey(url)) { try { URL img = new URL(url); images.put(url, new Image(null, img.openStream())); } catch (Exception e) { throw new RuntimeException(e.getMessage() + ": " + url); } } imageTimes.put(url, System.currentTimeMillis()); return images.get(url); }
00
Code Sample 1: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(QZ.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(QZ.PHRASES.getPhrase("26") + " " + QZ.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(QZ.PHRASES.getPhrase("19") + dest_name + QZ.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(QZ.PHRASES.getPhrase("31")); } else throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } } Code Sample 2: public 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); } }
11
Code Sample 1: public static boolean copy(File source, File target, boolean owrite) { if (!source.exists()) { log.error("Invalid input to copy: source " + source + "doesn't exist"); return false; } else if (!source.isFile()) { log.error("Invalid input to copy: source " + source + "isn't a file."); return false; } else if (target.exists() && !owrite) { log.error("Invalid input to copy: target " + target + " exists."); return false; } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); byte buffer[] = new byte[1024]; int read = -1; while ((read = in.read(buffer, 0, 1024)) != -1) out.write(buffer, 0, read); out.flush(); out.close(); in.close(); return true; } catch (IOException e) { log.error("Copy failed: ", e); return false; } } Code Sample 2: private void copyResourceToDir(String ondexDir, String resource) { InputStream inputStream = OndexGraphImpl.class.getClassLoader().getResourceAsStream(resource); try { FileWriter fileWriter = new FileWriter(new File(ondexDir, resource)); IOUtils.copy(inputStream, fileWriter); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { logger.error("Unable to copy '" + resource + "' file to " + ondexDir + "'"); } }
11
Code Sample 1: public static File createGzip(File inputFile) { File targetFile = new File(inputFile.getParentFile(), inputFile.getName() + ".gz"); if (targetFile.exists()) { log.warn("The target file '" + targetFile + "' already exists. Will overwrite"); } FileInputStream in = null; GZIPOutputStream out = null; try { int read = 0; byte[] data = new byte[BUFFER_SIZE]; in = new FileInputStream(inputFile); out = new GZIPOutputStream(new FileOutputStream(targetFile)); while ((read = in.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, read); } in.close(); out.close(); boolean deleteSuccess = inputFile.delete(); if (!deleteSuccess) { log.warn("Could not delete file '" + inputFile + "'"); } log.info("Successfully created gzip file '" + targetFile + "'."); } catch (Exception e) { log.error("Exception while creating GZIP.", e); } finally { StreamUtil.tryCloseStream(in); StreamUtil.tryCloseStream(out); } return targetFile; } Code Sample 2: public static boolean copy(InputStream is, File file) { try { IOUtils.copy(is, new FileOutputStream(file)); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } }
11
Code Sample 1: public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); } Code Sample 2: private File newFile(File oldFile) throws IOException { int counter = 0; File nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName()); while (nFile.exists()) { nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName() + "_" + counter); } IOUtils.copyFile(oldFile, nFile); return nFile; }
11
Code Sample 1: public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } } Code Sample 2: private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } }
00
Code Sample 1: public static final String encryptSHA(String decrypted) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(decrypted.getBytes()); byte hash[] = sha.digest(); sha.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: public static String md5(String text) { String encrypted = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); encrypted = hex(md.digest()); } catch (NoSuchAlgorithmException nsaEx) { } return encrypted; } Code Sample 2: public String[] getFriends() { InputStream is = null; String[] answer = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { answer = new String[1]; answer[0] = "none"; return answer; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray json = new JSONArray(result); answer = new String[json.length()]; for (int i = 0; i < json.length(); i++) { JSONObject jsonId = json.getJSONObject(i); answer[i] = jsonId.getString("uid"); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return answer; }
00
Code Sample 1: public String selectFROM() throws Exception { BufferedReader in = null; String data = null; try { HttpClient httpclient = new DefaultHttpClient(); URI uri = new URI("http://**.**.**.**/OctopusManager/index2.php"); HttpGet request = new HttpGet(); request.setURI(uri); HttpResponse httpresponse = httpclient.execute(request); HttpEntity httpentity = httpresponse.getEntity(); in = new BufferedReader(new InputStreamReader(httpentity.getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } } Code Sample 2: public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long time = System.currentTimeMillis(); String text = request.getParameter("text"); String parsedQueryString = request.getQueryString(); if (text == null) { String[] fonts = new File(ctx.getRealPath("/WEB-INF/fonts/")).list(); text = "accepted params: text,font,size,color,background,nocache,aa,break"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>"); out.println("Usage: " + request.getServletPath() + "?params[]<BR>"); out.println("Acceptable Params are: <UL>"); out.println("<LI><B>text</B><BR>"); out.println("The body of the image"); out.println("<LI><B>font</B><BR>"); out.println("Available Fonts (in folder '/WEB-INF/fonts/') <UL>"); for (int i = 0; i < fonts.length; i++) { if (!"CVS".equals(fonts[i])) { out.println("<LI>" + fonts[i]); } } out.println("</UL>"); out.println("<LI><B>size</B><BR>"); out.println("An integer, i.e. size=100"); out.println("<LI><B>color</B><BR>"); out.println("in rgb, i.e. color=255,0,0"); out.println("<LI><B>background</B><BR>"); out.println("in rgb, i.e. background=0,0,255"); out.println("transparent, i.e. background=''"); out.println("<LI><B>aa</B><BR>"); out.println("antialias (does not seem to work), aa=true"); out.println("<LI><B>nocache</B><BR>"); out.println("if nocache is set, we will write out the image file every hit. Otherwise, will write it the first time and then read the file"); out.println("<LI><B>break</B><BR>"); out.println("An integer greater than 0 (zero), i.e. break=20"); out.println("</UL>"); out.println("</UL>"); out.println("Example:<BR>"); out.println("&lt;img border=1 src=\"" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100\"&gt;<BR>"); out.println("<img border=1 src='" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100'><BR>"); out.println("</body>"); out.println("</html>"); return; } String myFile = (request.getQueryString() == null) ? "empty" : PublicEncryptionFactory.digestString(parsedQueryString).replace('\\', '_').replace('/', '_'); myFile = Config.getStringProperty("PATH_TO_TITLE_IMAGES") + myFile + ".png"; File file = new File(ctx.getRealPath(myFile)); if (!file.exists() || (request.getParameter("nocache") != null)) { StringTokenizer st = null; Iterator i = hm.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); if (parsedQueryString.indexOf(key) > -1) { String val = (String) entry.getValue(); parsedQueryString = UtilMethods.replace(parsedQueryString, key, val); } } st = new StringTokenizer(parsedQueryString, "&"); while (st.hasMoreTokens()) { try { String x = st.nextToken(); String key = x.split("=")[0]; String val = x.split("=")[1]; if ("text".equals(key)) { text = val; } } catch (Exception e) { } } text = URLDecoder.decode(text, "UTF-8"); Logger.debug(this.getClass(), "building title image:" + file.getAbsolutePath()); file.createNewFile(); try { String font_file = "/WEB-INF/fonts/arial.ttf"; if (request.getParameter("font") != null) { font_file = "/WEB-INF/fonts/" + request.getParameter("font"); } font_file = ctx.getRealPath(font_file); float size = 20.0f; if (request.getParameter("size") != null) { size = Float.parseFloat(request.getParameter("size")); } Color background = Color.white; if (request.getParameter("background") != null) { if (request.getParameter("background").equals("transparent")) try { background = new Color(Color.TRANSLUCENT); } catch (Exception e) { } else try { st = new StringTokenizer(request.getParameter("background"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); background = new Color(x, y, z); } catch (Exception e) { } } Color color = Color.black; if (request.getParameter("color") != null) { try { st = new StringTokenizer(request.getParameter("color"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); color = new Color(x, y, z); } catch (Exception e) { Logger.info(this, e.getMessage()); } } int intBreak = 0; if (request.getParameter("break") != null) { try { intBreak = Integer.parseInt(request.getParameter("break")); } catch (Exception e) { } } java.util.ArrayList<String> lines = null; if (intBreak > 0) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); int start = 0; String line = null; int offSet; for (; ; ) { try { for (; isWhitespace(text.charAt(start)); ++start) ; if (isWhitespace(text.charAt(start + intBreak - 1))) { lines.add(text.substring(start, start + intBreak)); start += intBreak; } else { for (offSet = -1; !isWhitespace(text.charAt(start + intBreak + offSet)); ++offSet) ; lines.add(text.substring(start, start + intBreak + offSet)); start += intBreak + offSet; } } catch (Exception e) { if (text.length() > start) lines.add(leftTrim(text.substring(start))); break; } } } else { java.util.StringTokenizer tokens = new java.util.StringTokenizer(text, "|"); if (tokens.hasMoreTokens()) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); for (; tokens.hasMoreTokens(); ) lines.add(leftTrim(tokens.nextToken())); } } Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(font_file)); font = font.deriveFont(size); BufferedImage buffer = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = buffer.createGraphics(); if (request.getParameter("aa") != null) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } FontRenderContext fc = g2.getFontRenderContext(); Rectangle2D fontBounds = null; Rectangle2D textLayoutBounds = null; TextLayout tl = null; boolean useTextLayout = false; useTextLayout = Boolean.parseBoolean(request.getParameter("textLayout")); int width = 0; int height = 0; int offSet = 0; if (1 < lines.size()) { int heightMultiplier = 0; int maxWidth = 0; for (; heightMultiplier < lines.size(); ++heightMultiplier) { fontBounds = font.getStringBounds(lines.get(heightMultiplier), fc); tl = new TextLayout(lines.get(heightMultiplier), font, fc); textLayoutBounds = tl.getBounds(); if (maxWidth < Math.ceil(fontBounds.getWidth())) maxWidth = (int) Math.ceil(fontBounds.getWidth()); } width = maxWidth; int boundHeigh = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); height = boundHeigh * lines.size(); offSet = ((int) (boundHeigh * 0.2)) * (lines.size() - 1); } else { fontBounds = font.getStringBounds(text, fc); tl = new TextLayout(text, font, fc); textLayoutBounds = tl.getBounds(); width = (int) fontBounds.getWidth(); height = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); } buffer = new BufferedImage(width, height - offSet, BufferedImage.TYPE_INT_ARGB); g2 = buffer.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(font); g2.setColor(background); if (!background.equals(new Color(Color.TRANSLUCENT))) g2.fillRect(0, 0, width, height); g2.setColor(color); if (1 < lines.size()) { for (int numLine = 0; numLine < lines.size(); ++numLine) { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(lines.get(numLine), 0, -y * (numLine + 1)); } } else { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(text, 0, -y); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(buffer, "png", out); out.close(); } catch (Exception ex) { Logger.info(this, ex.toString()); } } response.setContentType("image/png"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); OutputStream os = response.getOutputStream(); byte[] buf = new byte[4096]; int i = 0; while ((i = bis.read(buf)) != -1) { os.write(buf, 0, i); } os.close(); bis.close(); Logger.debug(this.getClass(), "time to build title: " + (System.currentTimeMillis() - time) + "ms"); return; }
00
Code Sample 1: public void parse(Project project, Object source, RootHandler handler) { AntXMLContext context = (AntXMLContext) Reflect.getField(handler, "context"); File buildFile = null; URL url = null; String buildFileName = null; if (source instanceof File) { buildFile = (File) source; buildFile = fu.normalize(buildFile.getAbsolutePath()); context.setBuildFile(buildFile); buildFileName = buildFile.toString(); } else if (source instanceof URL) { url = (URL) source; buildFileName = url.toString(); } else { throw new BuildException("Source " + source.getClass().getName() + " not supported by this plugin"); } InputStream inputStream = null; InputSource inputSource = null; try { XMLReader parser = JAXPUtils.getNamespaceXMLReader(); String uri = null; if (buildFile != null) { uri = fu.toURI(buildFile.getAbsolutePath()); inputStream = new FileInputStream(buildFile); } else { inputStream = url.openStream(); uri = url.toString(); } inputSource = new InputSource(inputStream); if (uri != null) { inputSource.setSystemId(uri); } project.log("parsing buildfile " + buildFileName + " with URI = " + uri, Project.MSG_VERBOSE); DefaultHandler hb = handler; parser.setContentHandler(hb); parser.setEntityResolver(hb); parser.setErrorHandler(hb); parser.setDTDHandler(hb); parser.parse(inputSource); } catch (SAXParseException exc) { Location location = new Location(exc.getSystemId(), exc.getLineNumber(), exc.getColumnNumber()); Throwable t = exc.getException(); if (t instanceof BuildException) { BuildException be = (BuildException) t; if (be.getLocation() == Location.UNKNOWN_LOCATION) { be.setLocation(location); } throw be; } throw new BuildException(exc.getMessage(), t, location); } catch (SAXException exc) { Throwable t = exc.getException(); if (t instanceof BuildException) { throw (BuildException) t; } throw new BuildException(exc.getMessage(), t); } catch (FileNotFoundException exc) { throw new BuildException(exc); } catch (UnsupportedEncodingException exc) { throw new BuildException("Encoding of project file " + buildFileName + " is invalid.", exc); } catch (IOException exc) { throw new BuildException("Error reading project file " + buildFileName + ": " + exc.getMessage(), exc); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { } } } } Code Sample 2: private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/png"); OutputStream outStream; outStream = resp.getOutputStream(); InputStream is; String name = req.getParameter("name"); if (name == null) { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } else { ImageRecord imageRecord = imageBean.getFile(name); if (imageRecord != null) { is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile())); } else { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } } IOUtils.copy(is, outStream); outStream.close(); outStream.flush(); } Code Sample 2: public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } }
11
Code Sample 1: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } Code Sample 2: @Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
00
Code Sample 1: public boolean import_status(String filename) { int pieceId; int i, j, col, row; int rotation; int number; boolean byurl = false; e2piece temppiece; String lineread; StringTokenizer tok; BufferedReader entree; try { if (byurl == true) { URL url = new URL(baseURL, filename); InputStream in = url.openStream(); entree = new BufferedReader(new InputStreamReader(in)); } else { entree = new BufferedReader(new FileReader(filename)); } pieceId = 0; for (i = 0; i < board.colnb; i++) { for (j = 0; j < board.rownb; j++) { unplace_piece_at(i, j); } } while (true) { lineread = entree.readLine(); if (lineread == null) { break; } tok = new StringTokenizer(lineread, " "); pieceId = Integer.parseInt(tok.nextToken()); col = Integer.parseInt(tok.nextToken()) - 1; row = Integer.parseInt(tok.nextToken()) - 1; rotation = Integer.parseInt(tok.nextToken()); place_piece_at(pieceId, col, row, 0); temppiece = board.get_piece_at(col, row); temppiece.reset_rotation(); temppiece.rotate(rotation); } return true; } catch (IOException err) { return false; } } Code Sample 2: public boolean checkTypeChange(Class<?> clazz, File buildDir, File refFile) throws MojoExecutionException { if (!clazz.isPrimitive()) { ClassLoader cl = clazz.getClassLoader(); if (cl == loader) { if (clazz.isArray()) return checkTypeChange(getArrayType(clazz), buildDir, refFile); String path = clazz.getName().replace('.', File.separatorChar) + ".class"; File file = new File(buildDir, path); long lastMod = Long.MAX_VALUE; if (!file.exists()) { URL url = cl.getResource(path); if (url == null) throw new MojoExecutionException("Can't get URL for webservice class '" + clazz.getName() + "' from jar file."); else { try { JarURLConnection con = (JarURLConnection) url.openConnection(); lastMod = con.getJarEntry().getTime(); } catch (IOException x) { throw new MojoExecutionException("Can't get modification time for webservice class '" + clazz.getName() + "' from jar file."); } } } else { lastMod = file.lastModified(); } if (refFile.lastModified() < lastMod) return true; if (clazz.isInterface()) { Class<?>[] itfs = clazz.getInterfaces(); for (int i = 0; i < itfs.length; i++) { boolean changed = checkTypeChange(itfs[i], buildDir, refFile); if (changed) return true; } } else { Class<?> sup = clazz.getSuperclass(); boolean changed = checkTypeChange(sup, buildDir, refFile); if (changed) return true; } } } return false; }
11
Code Sample 1: private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; } Code Sample 2: private void copy(File fin, File fout) throws IOException { FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(fout); in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } Code Sample 2: public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
11
Code Sample 1: private void _resetLanguages(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"; File from = new java.io.File(filePath); from.createNewFile(); String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File to = new java.io.File(tmpFilePath); 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 (IOException e) { Logger.debug(this, "Property File copy Failed " + e, e); } } } Code Sample 2: public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public static String MD5(String str, String encoding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.reset(); try { messageDigest.update(str.getBytes(encoding)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
00
Code Sample 1: public static InputStream getResourceAsStream(String resourceName) { try { URL url = getEmbeddedFileUrl(WS_SEP + resourceName); if (url != null) { return url.openStream(); } } catch (MalformedURLException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } catch (IOException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } return null; } Code Sample 2: public String getMD5Str(String str) { MessageDigest messageDigest = null; String mdStr = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } mdStr = md5StrBuff.toString(); return mdStr; }
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: 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); } }
11
Code Sample 1: @Override public void run() { try { FileChannel out = new FileOutputStream(outputfile).getChannel(); long pos = 0; status.setText("Slučovač: Proces Slučování spuštěn.. Prosím čekejte.."); for (int i = 1; i <= noofparts; i++) { FileChannel in = new FileInputStream(originalfilename.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Slučovač: Slučuji část " + i + ".."); this.splitsize = in.size(); out.transferFrom(in, pos, splitsize); pos += splitsize; in.close(); if (deleteOnFinish) new File(originalfilename + ".v" + i).delete(); pb.setValue(100 * i / noofparts); } out.close(); status.setText("Slučovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Sloučeno!", "Slučovač", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { } } Code Sample 2: public static void writeToFile(InputStream input, File file, ProgressListener listener, long length) { OutputStream output = null; try { output = new CountingOutputStream(new FileOutputStream(file), listener, length); IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
11
Code Sample 1: public static KUID createRandomID() { MessageDigestInput randomNumbers = new MessageDigestInput() { public void update(MessageDigest md) { byte[] random = new byte[LENGTH * 2]; GENERATOR.nextBytes(random); md.update(random); } }; MessageDigestInput properties = new MessageDigestInput() { public void update(MessageDigest md) { Properties props = System.getProperties(); try { for (Entry entry : props.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); md.update(key.getBytes("UTF-8")); md.update(value.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }; MessageDigestInput millis = new MessageDigestInput() { public void update(MessageDigest md) { long millis = System.currentTimeMillis(); md.update((byte) ((millis >> 56L) & 0xFFL)); md.update((byte) ((millis >> 48L) & 0xFFL)); md.update((byte) ((millis >> 40L) & 0xFFL)); md.update((byte) ((millis >> 32L) & 0xFFL)); md.update((byte) ((millis >> 24L) & 0xFFL)); md.update((byte) ((millis >> 16L) & 0xFFL)); md.update((byte) ((millis >> 8L) & 0xFFL)); md.update((byte) ((millis) & 0xFFL)); } }; MessageDigestInput nanos = new MessageDigestInput() { public void update(MessageDigest md) { long nanos = System.nanoTime(); md.update((byte) ((nanos >> 56L) & 0xFFL)); md.update((byte) ((nanos >> 48L) & 0xFFL)); md.update((byte) ((nanos >> 40L) & 0xFFL)); md.update((byte) ((nanos >> 32L) & 0xFFL)); md.update((byte) ((nanos >> 24L) & 0xFFL)); md.update((byte) ((nanos >> 16L) & 0xFFL)); md.update((byte) ((nanos >> 8L) & 0xFFL)); md.update((byte) ((nanos) & 0xFFL)); } }; MessageDigestInput[] input = { properties, randomNumbers, millis, nanos }; Arrays.sort(input); try { MessageDigest md = MessageDigest.getInstance("SHA1"); for (MessageDigestInput mdi : input) { mdi.update(md); int hashCode = System.identityHashCode(mdi); md.update((byte) ((hashCode >> 24) & 0xFF)); md.update((byte) ((hashCode >> 16) & 0xFF)); md.update((byte) ((hashCode >> 8) & 0xFF)); md.update((byte) ((hashCode) & 0xFF)); md.update((byte) ((mdi.rnd >> 24) & 0xFF)); md.update((byte) ((mdi.rnd >> 16) & 0xFF)); md.update((byte) ((mdi.rnd >> 8) & 0xFF)); md.update((byte) ((mdi.rnd) & 0xFF)); } return new KUID(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } Code Sample 2: protected static String getInitialUUID() { if (myRand == null) { myRand = new Random(); } long rand = myRand.nextLong(); String sid; try { sid = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { sid = Thread.currentThread().getName(); } StringBuffer sb = new StringBuffer(); sb.append(sid); sb.append(":"); sb.append(Long.toString(rand)); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new OMException(e); } md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); StringBuffer sb2 = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; sb2.append(Integer.toHexString(b)); } int begin = myRand.nextInt(); if (begin < 0) begin = begin * -1; begin = begin % 8; return sb2.toString().substring(begin, begin + 18).toUpperCase(); }
00
Code Sample 1: public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException { log.debug("copyLocalFileAsTempFileInExternallyAccessableDir"); File f = this.createTempFileInExternallyAccessableDir(); FileChannel srcChannel = new FileInputStream(localFileRef).getChannel(); FileChannel dstChannel = new FileOutputStream(f).getChannel(); log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef + " to dest-outputStream: " + f.getAbsolutePath()); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath()); return f; } Code Sample 2: @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; }
00
Code Sample 1: public Object run() { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { userHome + sep + ".themes", System.getProperty("swing.metacitythemedir"), "/usr/share/themes", "/usr/gnome/share/themes", "/opt/gnome2/share/themes" }; URL themeDir = null; for (int i = 0; i < dirs.length; i++) { if (dirs[i] == null) { continue; } File dir = new File(dirs[i] + sep + arg + sep + "metacity-1"); if (new File(dir, "metacity-theme-1.xml").canRead()) { try { themeDir = dir.toURL(); } catch (MalformedURLException ex) { themeDir = null; } break; } } if (themeDir == null) { String filename = "resources/metacity/" + arg + "/metacity-1/metacity-theme-1.xml"; URL url = getClass().getResource(filename); if (url != null) { String str = url.toString(); try { themeDir = new URL(str.substring(0, str.lastIndexOf('/')) + "/"); } catch (MalformedURLException ex) { themeDir = null; } } } return themeDir; } else if (type == GET_USER_THEME) { try { userHome = System.getProperty("user.home"); String theme = System.getProperty("swing.metacitythemename"); if (theme != null) { return theme; } URL url = new URL(new File(userHome).toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); char[] buf = new char[1024]; StringBuffer strBuf = new StringBuffer(); int n; while ((n = reader.read(buf)) >= 0) { strBuf.append(buf, 0, n); } reader.close(); String str = strBuf.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); int i = strLowerCase.indexOf("<entry name=\"theme\""); if (i >= 0) { i = strLowerCase.indexOf("<stringvalue>", i); if (i > 0) { i += "<stringvalue>".length(); int i2 = str.indexOf("<", i); return str.substring(i, i2); } } } } catch (MalformedURLException ex) { } catch (IOException ex) { } return null; } else if (type == GET_IMAGE) { return new ImageIcon((URL) arg).getImage(); } else { return null; } } Code Sample 2: public void doImport(File f, boolean checkHosp) throws Exception { connector.getConnection().setAutoCommit(false); File base = f.getParentFile(); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String outFileName = entry.getName(); File outFile = new File(base, outFileName); OutputStream out = new FileOutputStream(outFile, false); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); } in.close(); importDirectory(base, checkHosp); connector.getConnection().commit(); }
00
Code Sample 1: public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; try { md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException nsae) { throw nsae; } catch (UnsupportedEncodingException uee) { throw uee; } return (new BigInteger(1, md.digest())).toString(16); } Code Sample 2: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); }
11
Code Sample 1: private static void replaceEntityMappings(File signserverearpath, File entityMappingXML) throws ZipException, IOException { ZipInputStream earFile = new ZipInputStream(new FileInputStream(signserverearpath)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream tempZip = new ZipOutputStream(baos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("signserver-ejb.jar")) { content = replaceEntityMappings(content, entityMappingXML); next = new ZipEntry("signserver-ejb.jar"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); FileOutputStream fos = new FileOutputStream(signserverearpath); fos.write(baos.toByteArray()); fos.close(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private static String hashToMD5(String sig) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(sig.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032X", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } } Code Sample 2: public String calculateProjectMD5(String scenarioName) throws Exception { Scenario s = ScenariosManager.getInstance().getScenario(scenarioName); s.loadParametersAndValues(); String scenarioMD5 = calculateScenarioMD5(s); Map<ProjectComponent, String> map = getProjectMD5(new ProjectComponent[] { ProjectComponent.resources, ProjectComponent.classes, ProjectComponent.suts, ProjectComponent.libs }); map.put(ProjectComponent.currentScenario, scenarioMD5); MessageDigest md = MessageDigest.getInstance("MD5"); Iterator<String> iter = map.values().iterator(); while (iter.hasNext()) { md.update(iter.next().getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
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 ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
00
Code Sample 1: private static String getDigest(String srcStr, String alg) { Assert.notNull(srcStr); Assert.notNull(alg); try { MessageDigest alga = MessageDigest.getInstance(alg); alga.update(srcStr.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public List<Mosque> getAllMosquaisFromDataBase() { List<Mosque> mosquais = new ArrayList<Mosque>(); InputStream is = null; String result = ""; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (MyMapActivity.DEVELOPER_MODE) { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.mLatitude + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.mLongitude + "")); } else { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.myLocation.getLatitude() + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.myLocation.getLongitude() + "")); } nameValuePairs.add(new BasicNameValuePair(Param.RAYON, DataBaseQuery.rayon * Param.KM_MARGE + "")); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Param.URI_SELECT_ALL_DATA_BASE); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); Mosque mosquai = new Mosque(json_data.getInt(Param.ID), json_data.getString(Param.NOM), json_data.getDouble(Param.LATITUDE), json_data.getDouble(Param.LONGITUDE), json_data.getString(Param.INFO), json_data.getInt(Param.HAVE_PICTURE) == 1 ? true : false, json_data.getString(Param.PICTURE)); mosquais.add(mosquai); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return mosquais; }
00
Code Sample 1: public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public static Image readImage(URL url, ImageMimeType type, int page) throws IOException { if (type.javaNativeSupport()) { return ImageIO.read(url.openStream()); } else if ((type.equals(ImageMimeType.DJVU)) || (type.equals(ImageMimeType.VNDDJVU)) || (type.equals(ImageMimeType.XDJVU))) { com.lizardtech.djvu.Document doc = new com.lizardtech.djvu.Document(url); doc.setAsync(false); DjVuPage[] p = new DjVuPage[1]; int size = doc.size(); if ((page != 0) && (page >= size)) { page = 0; } p[0] = doc.getPage(page, 1, true); p[0].setAsync(false); DjVuImage djvuImage = new DjVuImage(p, true); Rectangle pageBounds = djvuImage.getPageBounds(0); Image[] images = djvuImage.getImage(new JPanel(), new Rectangle(pageBounds.width, pageBounds.height)); if (images.length == 1) { Image img = images[0]; return img; } else return null; } else if (type.equals(ImageMimeType.PDF)) { PDDocument document = null; try { document = PDDocument.load(url.openStream()); int resolution = 96; List<?> pages = document.getDocumentCatalog().getAllPages(); PDPage pdPage = (PDPage) pages.get(page); BufferedImage image = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, resolution); return image; } finally { if (document != null) { document.close(); } } } else throw new IllegalArgumentException("unsupported mimetype '" + type.getValue() + "'"); }
00
Code Sample 1: public Long addRole(AuthSession authSession, RoleBean roleBean) { PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_AUTH_ACCESS_GROUP"); seq.setTableName("WM_AUTH_ACCESS_GROUP"); seq.setColumnName("ID_ACCESS_GROUP"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_AUTH_ACCESS_GROUP " + "( ID_ACCESS_GROUP, NAME_ACCESS_GROUP ) values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); RsetTools.setLong(ps, 1, sequenceValue); ps.setString(2, roleBean.getName()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new role"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public static String encrypt(String text) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String result = ""; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes()); byte[] hash = digest.digest(); char buffer[] = new char[hash.length * 2]; for (int i = 0, x = 0; i < hash.length; i++) { buffer[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; buffer[x++] = HEX_CHARS[hash[i] & 0xf]; } result = new String(buffer); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
11
Code Sample 1: public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException { ZipFile zip = new ZipFile(mapPackFile); try { Enumeration<? extends ZipEntry> entries = zip.entries(); MessageDigest md5Total = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5"); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; String name = entry.getName(); if (name.toUpperCase().startsWith("META-INF")) continue; md5.reset(); InputStream in = zip.getInputStream(entry); byte[] data = Utilities.getInputBytes(in); in.close(); byte[] digest = md5.digest(data); log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\""); md5Total.update(digest); md5Total.update(name.getBytes()); } String md5sum = Hex.encodeHexString(md5Total.digest()); log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum); return md5sum; } finally { zip.close(); } } Code Sample 2: public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
11
Code Sample 1: public static String digest(String str) { StringBuffer sb = new StringBuffer(); try { MessageDigest md5 = MessageDigest.getInstance("md5"); md5.update(str.getBytes("ISO8859-1")); byte[] array = md5.digest(); for (int x = 0; x < 16; x++) { if ((array[x] & 0xff) < 0x10) sb.append("0"); sb.append(Long.toString(array[x] & 0xff, 16)); } } catch (Exception e) { System.out.println(e); } return sb.toString(); } Code Sample 2: public String getMD5String(String par1Str) { try { String s = (new StringBuilder()).append(field_27370_a).append(par1Str).toString(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); messagedigest.update(s.getBytes(), 0, s.length()); return (new BigInteger(1, messagedigest.digest())).toString(16); } catch (NoSuchAlgorithmException nosuchalgorithmexception) { throw new RuntimeException(nosuchalgorithmexception); } }
00
Code Sample 1: public String getFeatureInfoHTML(Point3d GKposition, String[] layerIds, int featureCount) { String html = ""; try { String request = null; if (version == VERSION_030) { org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } else if (version == VERSION_040) { org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } else if (version == VERSION_041) { org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } if (Navigator.isVerbose()) System.out.println(request); URL url = new URL(request); int contentLength = -1; URLConnection urlc; urlc = url.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); if (getEncoding() != null) { urlc.setRequestProperty("Authorization", "Basic " + getEncoding()); } urlc.connect(); String content_type = urlc.getContentType(); if (content_type.equalsIgnoreCase("text/html") || content_type.equalsIgnoreCase("text/html;charset=UTF-8")) { InputStream is = urlc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); StringBuffer sb = new StringBuffer(); InputStreamReader isr = new InputStreamReader(bis); char chars[] = new char[10240]; int len = 0; contentLength = 0; while ((len = isr.read(chars, 0, chars.length)) >= 0) { sb.append(chars, 0, len); contentLength += len; } chars = null; isr.close(); bis.close(); is.close(); html = sb.toString(); } } catch (Exception e) { e.printStackTrace(); } return html; } Code Sample 2: public InputStream getResourceAsStream(String name) { InputStream is = parent.getResourceAsStream(name); if (is == null) { URL url = findResource(name); if (url != null) { try { is = url.openStream(); } catch (IOException e) { is = null; } } } return is; }
11
Code Sample 1: public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; } Code Sample 2: private void copyResourceToDir(String ondexDir, String resource) { InputStream inputStream = OndexGraphImpl.class.getClassLoader().getResourceAsStream(resource); try { FileWriter fileWriter = new FileWriter(new File(ondexDir, resource)); IOUtils.copy(inputStream, fileWriter); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { logger.error("Unable to copy '" + resource + "' file to " + ondexDir + "'"); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); System.out.println("\n"); in.seek(0); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } } 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: protected void doProxyInternally(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpRequestBase proxyReq = buildProxyRequest(req); URI reqUri = proxyReq.getURI(); String cookieDomain = reqUri.getHost(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute("org.atricorel.idbus.kernel.main.binding.http.HttpServletRequest", req); int intIdx = 0; for (int i = 0; i < httpClient.getRequestInterceptorCount(); i++) { if (httpClient.getRequestInterceptor(i) instanceof RequestAddCookies) { intIdx = i; break; } } IDBusRequestAddCookies interceptor = new IDBusRequestAddCookies(cookieDomain); httpClient.removeRequestInterceptorByClass(RequestAddCookies.class); httpClient.addRequestInterceptor(interceptor, intIdx); httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (logger.isTraceEnabled()) logger.trace("Staring to follow redirects for " + req.getPathInfo()); HttpResponse proxyRes = null; List<Header> storedHeaders = new ArrayList<Header>(40); boolean followTargetUrl = true; byte[] buff = new byte[1024]; while (followTargetUrl) { if (logger.isTraceEnabled()) logger.trace("Sending internal request " + proxyReq); proxyRes = httpClient.execute(proxyReq, httpContext); String targetUrl = null; Header[] headers = proxyRes.getAllHeaders(); for (Header header : headers) { if (header.getName().equals("Server")) continue; if (header.getName().equals("Transfer-Encoding")) continue; if (header.getName().equals("Location")) continue; if (header.getName().equals("Expires")) continue; if (header.getName().equals("Content-Length")) continue; if (header.getName().equals("Content-Type")) continue; storedHeaders.add(header); } if (logger.isTraceEnabled()) logger.trace("HTTP/STATUS:" + proxyRes.getStatusLine().getStatusCode() + "[" + proxyReq + "]"); switch(proxyRes.getStatusLine().getStatusCode()) { case 200: followTargetUrl = false; break; case 404: followTargetUrl = false; break; case 500: followTargetUrl = false; break; case 302: Header location = proxyRes.getFirstHeader("Location"); targetUrl = location.getValue(); if (!internalProcessingPolicy.match(req, targetUrl)) { if (logger.isTraceEnabled()) logger.trace("Do not follow HTTP 302 to [" + location.getValue() + "]"); Collections.addAll(storedHeaders, proxyRes.getHeaders("Location")); followTargetUrl = false; } else { if (logger.isTraceEnabled()) logger.trace("Do follow HTTP 302 to [" + location.getValue() + "]"); followTargetUrl = true; } break; default: followTargetUrl = false; break; } HttpEntity entity = proxyRes.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { if (!followTargetUrl) { for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } IOUtils.copy(instream, res.getOutputStream()); res.getOutputStream().flush(); } else { int r = instream.read(buff); int total = r; while (r > 0) { r = instream.read(buff); total += r; } if (total > 0) logger.warn("Ignoring response content size : " + total); } } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { proxyReq.abort(); throw ex; } finally { try { instream.close(); } catch (Exception ignore) { } } } else { if (!followTargetUrl) { res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } } } if (followTargetUrl) { proxyReq = buildProxyRequest(targetUrl); httpContext = null; } } if (logger.isTraceEnabled()) logger.trace("Ended following redirects for " + req.getPathInfo()); } Code Sample 2: private void saveCampaign() throws HeadlessException { try { dbConnection.setAutoCommit(false); dbConnection.setSavepoint(); String sql = "UPDATE campaigns SET " + "queue = ? ," + "adjustRatioPeriod = ?, " + "asterisk = ?, " + "context = ?," + "extension = ?, " + "dialContext = ?, " + "dialPrefix = ?," + "dialTimeout = ?, " + "dialingMethod = ?," + "dialsPerFreeResourceRatio = ?, " + "maxIVRChannels = ?, " + "maxDialingThreads = ?," + "maxDialsPerFreeResourceRatio = ?," + "minDialsPerFreeResourceRatio = ?, " + "maxTries = ?, " + "firstRetryAfterMinutes = ?," + "secondRetryAfterMinutes = ?, " + "furtherRetryAfterMinutes = ?, " + "startDate = ?, " + "endDate = ?," + "popUpURL = ?, " + "contactBatchSize = ?, " + "retriesBatchPct = ?, " + "reschedulesBatchPct = ?, " + "allowReschedule = ?, " + "rescheduleToOnself = ?, " + "script = ?," + "agentsCanUpdateContacts = ?, " + "hideContactFields = ?, " + "afterCallWork = ?, " + "reserveAvailableAgents = ?, " + "useDNCList = ?, " + "enableAgentDNC = ?, " + "contactsFilter = ?, " + "DNCTo = ?," + "callRecordingPolicy = ?, " + "callRecordingPercent = ?, " + "callRecordingMaxAge = ?, " + "WHERE name = ?"; PreparedStatement statement = dbConnection.prepareStatement(sql); int i = 1; statement.setString(i++, txtQueue.getText()); statement.setInt(i++, Integer.valueOf(txtAdjustRatio.getText())); statement.setString(i++, ""); statement.setString(i++, txtContext.getText()); statement.setString(i++, txtExtension.getText()); statement.setString(i++, txtDialContext.getText()); statement.setString(i++, txtDialPrefix.getText()); statement.setInt(i++, 30000); statement.setInt(i++, cboDialingMethod.getSelectedIndex()); statement.setFloat(i++, Float.valueOf(txtInitialDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxIVRChannels.getText())); statement.setInt(i++, Integer.valueOf(txtDialLimit.getText())); statement.setFloat(i++, Float.valueOf(txtMaxDialingRatio.getText())); statement.setFloat(i++, Float.valueOf(txtMinDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxRetries.getText())); statement.setInt(i++, Integer.valueOf(txtFirstRetry.getText())); statement.setInt(i++, Integer.valueOf(txtSecondRetry.getText())); statement.setInt(i++, Integer.valueOf(txtFurtherRetries.getText())); statement.setDate(i++, Date.valueOf(txtStartDate.getText())); statement.setDate(i++, Date.valueOf(txtEndDate.getText())); statement.setString(i++, txtURL.getText()); statement.setInt(i++, Integer.valueOf(txtContactBatchSize.getText())); statement.setInt(i++, Integer.valueOf(txtRetryBatchPct.getText())); statement.setInt(i++, Integer.valueOf(txtRescheduleBatchPct.getText())); statement.setInt(i++, chkAgentCanReschedule.isSelected() ? 1 : 0); statement.setInt(i++, chkAgentCanRescheduleSelf.isSelected() ? 1 : 0); statement.setString(i++, txtScript.getText()); statement.setInt(i++, chkAgentCanUpdateContacts.isSelected() ? 1 : 0); statement.setString(i++, ""); statement.setInt(i++, Integer.valueOf(txtACW.getText())); statement.setInt(i++, Integer.valueOf(txtReserveAgents.getText())); statement.setInt(i++, cboDNCListPreference.getSelectedIndex()); statement.setInt(i++, 1); statement.setString(i++, ""); statement.setInt(i++, 0); statement.setInt(i++, cboRecordingPolicy.getSelectedIndex()); statement.setInt(i++, Integer.valueOf(txtRecordingPct.getText())); statement.setInt(i++, Integer.valueOf(txtRecordingMaxAge.getText())); statement.setString(i++, campaign); statement.executeUpdate(); dbConnection.commit(); } catch (SQLException ex) { try { dbConnection.rollback(); } catch (SQLException ex1) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1); } JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex); } }
00
Code Sample 1: public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
11
Code Sample 1: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } 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: @Override public void doExecute(String[] args) { if (args.length != 2) { printUsage(); } else { int fileNo = 0; try { fileNo = Integer.parseInt(args[1]) - 1; } catch (NumberFormatException e) { printUsage(); return; } if (fileNo < 0) { printUsage(); return; } StorageFile[] files = (StorageFile[]) ctx.getRemoteDir().listFiles(); try { StorageFile file = files[fileNo]; File outFile = getOutFile(file); FileOutputStream out = new FileOutputStream(outFile); InputStream in = file.openStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); afterSave(outFile); if (outFile.exists()) { print("File written to: " + outFile.getAbsolutePath()); } } catch (IOException e) { printError("Failed to load file. " + e.getMessage()); } catch (Exception e) { printUsage(); return; } } } Code Sample 2: public ProgramMessageSymbol addProgramMessageSymbol(int programID, String name, byte[] bytecode) throws AdaptationException { ProgramMessageSymbol programMessageSymbol = null; Connection connection = null; PreparedStatement preparedStatement = null; Statement statement = null; ResultSet resultSet = null; InputStream stream = new ByteArrayInputStream(bytecode); try { String query = "INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES ( ?, ?, ? )"; connection = DriverManager.getConnection(CONN_STR); preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, programID); preparedStatement.setString(2, name); preparedStatement.setBinaryStream(3, stream, bytecode.length); log.info("INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES (" + programID + ", '" + name + "', " + "<bytecode>)"); preparedStatement.executeUpdate(); statement = connection.createStatement(); query = "SELECT * FROM ProgramMessageSymbols WHERE " + "programID = " + programID + " AND " + "name = '" + name + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to add program message symbol failed."; log.error(msg); ; throw new AdaptationException(msg); } programMessageSymbol = getProgramMessageSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in addProgramMessageSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { preparedStatement.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programMessageSymbol; }
00
Code Sample 1: public void storeArticles(Context ctx, RSSFeed feed) throws RSSHandlerError { try { mFeed = feed; db = new RSSDB(ctx); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); InputStream stream = feed.url.openStream(); InputSource source = new InputSource(stream); xr.parse(source); } catch (IOException e) { Log.e("GeneriCast", e.toString()); throw new RSSHandlerError("IOError"); } catch (SAXException e) { Log.e("GeneriCast", e.toString()); throw new RSSHandlerError("ParsingError"); } catch (ParserConfigurationException e) { Log.e("GeneriCast", e.toString()); throw new RSSHandlerError("ParsingError"); } } Code Sample 2: public void actionPerformed(ActionEvent e) { String line, days; String oldType, newType; String dept = ""; buttonPressed = true; char first; int caretIndex; int tempIndex; int oldDisplayNum = displayNum; for (int i = 0; i < 10; i++) { if (e.getSource() == imageButtons[i]) { if (rePrintAnswer) printAnswer(); print.setVisible(true); selectTerm.setVisible(true); displayNum = i; textArea2.setCaretPosition(textArea2.getText().length() - 1); caretIndex = textArea2.getText().indexOf("#" + (i + 1)); if (caretIndex != -1) textArea2.setCaretPosition(caretIndex); repaint(); } } if (e.getSource() == print) { if (textArea2.getText().charAt(0) != '#') printAnswer(); String data = textArea2.getText(); int start = data.indexOf("#" + (displayNum + 1)); start = data.indexOf("\n", start); start++; int end = data.indexOf("\n---------", start); data = data.substring(start, end); String tr = ""; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String s = getCodeBase().toString() + "schedule.cgi?term=" + tr + "&data=" + URLEncoder.encode(data); try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == webSite) { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); String s = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(lst.getSelectedItem().toString()) + "&p_course=" + num; try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == loadButton) { printSign("Loading..."); String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); String text = readURL(fileName); if (!publicSign.equals("Error loading.")) { textArea1.setText(text); fileName += ".2"; text = readURL(fileName); absorb(text); printAnswer(); for (int i = 0; i < 10; i++) { if (answer[i].gap != -1 && answer[i].gap != 9999 && answer[i].gap != 10000) { imageButtons[i].setVisible(true); } else imageButtons[i].setVisible(false); } if (!imageButtons[0].isVisible()) { print.setVisible(false); selectTerm.setVisible(false); } else { print.setVisible(true); selectTerm.setVisible(true); } printSign("Load complete."); } displayNum = 0; repaint(); } if (e.getSource() == saveButton) { String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); printSign("Saving..."); writeURL(fileName, 1); printSign("Saving......"); fileName += ".2"; writeURL(fileName, 2); printSign("Save complete."); } if (e.getSource() == instructions) { showInstructions(); } if (e.getSource() == net) { drawWarning = false; String inputLine = ""; String text = ""; String out; String urlIn = ""; textArea2.setText("Retrieving Data..."); try { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); dept = lst.getSelectedItem().toString(); { urlIn = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(dept) + "&p_course=" + num; try { URL url = new URL(getCodeBase().toString() + "getURL.cgi"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); DataOutputStream out2 = new DataOutputStream(con.getOutputStream()); String content = "url=" + URLEncoder.encode(urlIn); out2.writeBytes(content); out2.flush(); DataInputStream in = new DataInputStream(con.getInputStream()); String s; while ((s = in.readLine()) != null) { } in.close(); } catch (IOException err) { } } URL yahoo = new URL(this.getCodeBase(), "classData.txt"); URLConnection yc = yahoo.openConnection(); StringBuffer buf = new StringBuffer(""); DataInputStream in = new DataInputStream(new BufferedInputStream(yc.getInputStream())); while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } text = buf.toString(); in.close(); } catch (IOException errr) { } String inText = (parseData(text, false)); if (inText.equals("-1")) inText = parseData(text, true); if (inText.equals("\n")) { textArea2.append("\nNO DATA FOUND \n(" + urlIn + ")"); } else textArea1.append(inText); repaint(); } badInput = false; if (e.getSource() == button1) { if (t != null && t.isAlive()) { t.stop(); epilogue(); return; } displayNum = 0; textArea2.setCaretPosition(0); for (int i = 0; i < 30; i++) for (int j = 0; j < 20; j++) { matrix[i][j] = new entry(); matrix[i][j].time = new Time[4]; for (int k = 0; k < 4; k++) { matrix[i][j].time[k] = new Time(); matrix[i][j].time[k].from = 0; } } val = new entry[30]; for (int i = 0; i < 30; i++) { val[i] = new entry(); val[i].time = new Time[4]; for (int j = 0; j < 4; j++) { val[i].time[j] = new Time(); val[i].time[j].from = 0; } } oldPercentDone = -5; oldAmountDone = -1 * PRINTINTERVAL; percentDone = 0; amountDone = 0; drawWarning = false; errorMessage = ""; String text1 = textArea1.getText(); if (text1.toUpperCase().indexOf("OR:") == -1) containsOR = false; else containsOR = true; text1 = removeOR(text1.toUpperCase()); StringTokenizer st = new StringTokenizer(text1, "\n"); clss = -1; timeEntry = -1; boolean noTimesListed = false; while (st.hasMoreTokens()) { line = st.nextToken().toString(); if (line.equals("")) break; else first = line.charAt(0); if (first == '0') { badInput = true; repaint(); break; } if (first >= '1' && first <= '9') { noTimesListed = false; timeEntry++; if (timeEntry == 30) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 30 time entries per class."); badInput = true; repaint(); return; } nextTime = -1; StringTokenizer andST = new StringTokenizer(line, ","); while (andST.hasMoreTokens()) { String temp; String entry; int index, fromTime, toTime; nextTime++; if (nextTime == 4) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 4 time intervals per entry!"); badInput = true; repaint(); return; } StringTokenizer timeST = new StringTokenizer(andST.nextToken()); temp = timeST.nextToken().toString(); entry = ""; index = 0; if (temp.equals("")) break; while (temp.charAt(index) != '-') { entry += temp.charAt(index); index++; if (index >= temp.length()) { rePrintAnswer = true; textArea2.setText("Error: There should be no space before hyphens."); badInput = true; repaint(); return; } } try { fromTime = Integer.parseInt(entry); } catch (NumberFormatException re) { rePrintAnswer = true; textArea2.setText("Error: There should be no a/p sign after FROM_TIME."); badInput = true; repaint(); return; } index++; entry = ""; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } while (temp.charAt(index) >= '0' && temp.charAt(index) <= '9') { entry += temp.charAt(index); index++; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } } toTime = Integer.parseInt(entry); if (temp.charAt(index) == 'a' || temp.charAt(index) == 'A') { } else { if (isLesse(fromTime, toTime) && !timeEq(toTime, 1200)) { if (String.valueOf(fromTime).length() == 4 || String.valueOf(fromTime).length() == 3) { fromTime += 1200; } else fromTime += 12; } if (!timeEq(toTime, 1200)) { if (String.valueOf(toTime).length() == 4 || String.valueOf(toTime).length() == 3) { toTime += 1200; } else toTime += 12; } } if (String.valueOf(fromTime).length() == 2 || String.valueOf(fromTime).length() == 1) fromTime *= 100; if (String.valueOf(toTime).length() == 2 || String.valueOf(toTime).length() == 1) toTime *= 100; matrix[timeEntry][clss].time[nextTime].from = fromTime; matrix[timeEntry][clss].time[nextTime].to = toTime; if (timeST.hasMoreTokens()) days = timeST.nextToken().toString(); else { rePrintAnswer = true; textArea2.setText("Error: days not specified?"); badInput = true; repaint(); return; } if (days.equals("")) return; if (days.indexOf("M") != -1 || days.indexOf("m") != -1) matrix[timeEntry][clss].time[nextTime].m = 1; if (days.indexOf("TU") != -1 || days.indexOf("Tu") != -1 || days.indexOf("tu") != -1) matrix[timeEntry][clss].time[nextTime].tu = 1; if (days.indexOf("W") != -1 || days.indexOf("w") != -1) matrix[timeEntry][clss].time[nextTime].w = 1; if (days.indexOf("TH") != -1 || days.indexOf("Th") != -1 || days.indexOf("th") != -1) matrix[timeEntry][clss].time[nextTime].th = 1; if (days.indexOf("F") != -1 || days.indexOf("f") != -1) matrix[timeEntry][clss].time[nextTime].f = 1; } } else { if (noTimesListed) clss--; clss++; if (clss == 20) { rePrintAnswer = true; textArea2.setText("Error: No more than 20 class entries!"); badInput = true; repaint(); return; } timeEntry = -1; line = line.trim(); for (int i = 0; i < 30; i++) matrix[i][clss].name = line; noTimesListed = true; } } for (int i = 0; i < 30; i++) { for (int j = 0; j < 4; j++) { val[i].time[j].from = 0; } } for (int i = 0; i < 10; i++) { beat10[i] = 10000; answer[i].gap = 10000; for (int j = 0; j < 30; j++) answer[i].classes[j].name = ""; } time = 0; calcTotal = 0; int k = 0; calculateTotalPercent(0, "\n"); amountToReach = calcTotal; button1.setLabel("...HALT GENERATION..."); printWarn(); if (t != null && t.isAlive()) t.stop(); t = new Thread(this, "Generator"); t.start(); } }
00
Code Sample 1: public static String hashMD5(String baseString) { MessageDigest digest = null; StringBuffer hexString = new StringBuffer(); try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(baseString.getBytes()); byte[] hash = digest.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Password.class.getName()).log(Level.SEVERE, null, ex); } return hexString.toString(); } Code Sample 2: public void run() { try { File f = new File(repository + fileName); if (!f.exists()) { URL url = new URL(urlString); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream dis = url.openStream(); File dir = new File(repository); if (!dir.exists()) dir.mkdirs(); f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); byte[] buffer = new byte[4096]; int len = 0; while ((len = dis.read(buffer)) > -1) fos.write(buffer, 0, len); fos.close(); dis.close(); } fireFileDownloadedListener(fileName); } catch (Exception e) { e.printStackTrace(); } }