label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public String postData(String result, DefaultHttpClient httpclient) { try { HttpPost post = new HttpPost("http://3dforandroid.appspot.com/api/v1/note/create"); StringEntity se = new StringEntity(result); se.setContentEncoding(HTTP.UTF_8); se.setContentType("application/json"); post.setEntity(se); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "*/*"); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); InputStream instream; instream = entity.getContent(); responseMessage = read(instream); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseMessage; }
Code Sample 2:
public void performUpdates(List<PackageDescriptor> downloadList, ProgressListener progressListener) throws IOException, UpdateServiceException_Exception { int i = 0; try { for (PackageDescriptor desc : downloadList) { String urlString = service.getDownloadURL(desc.getPackageId(), desc.getVersion(), desc.getPlatformName()); int minProgress = 20 + 80 * i / downloadList.size(); int maxProgress = 20 + 80 * (i + 1) / downloadList.size(); boolean incremental = UpdateManager.isIncrementalUpdate(); if (desc.getPackageTypeName().equals("RAPIDMINER_PLUGIN")) { ManagedExtension extension = ManagedExtension.getOrCreate(desc.getPackageId(), desc.getName(), desc.getLicenseName()); String baseVersion = extension.getLatestInstalledVersionBefore(desc.getVersion()); incremental &= baseVersion != null; URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(baseVersion, "UTF-8") : "")).toURL(); if (incremental) { LogService.getRoot().info("Updating " + desc.getPackageId() + " incrementally."); try { updatePluginIncrementally(extension, openStream(url, progressListener, minProgress, maxProgress), baseVersion, desc.getVersion()); } catch (IOException e) { LogService.getRoot().warning("Incremental Update failed. Trying to fall back on non incremental Update..."); incremental = false; } } if (!incremental) { LogService.getRoot().info("Updating " + desc.getPackageId() + "."); updatePlugin(extension, openStream(url, progressListener, minProgress, maxProgress), desc.getVersion()); } extension.addAndSelectVersion(desc.getVersion()); } else { URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(RapidMiner.getLongVersion(), "UTF-8") : "")).toURL(); LogService.getRoot().info("Updating RapidMiner core."); updateRapidMiner(openStream(url, progressListener, minProgress, maxProgress), desc.getVersion()); } i++; progressListener.setCompleted(20 + 80 * i / downloadList.size()); } } catch (URISyntaxException e) { throw new IOException(e); } finally { progressListener.complete(); } }
|
11
|
Code Sample 1:
public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); }
Code Sample 2:
public static String toMD5Sum(String arg0) { String ret; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(arg0.getBytes()); ret = toHexString(md.digest()); } catch (Exception e) { ret = arg0; } return ret; }
|
11
|
Code Sample 1:
public void save(File f, AudioFileFormat.Type t) throws IOException { if (t.getExtension().equals("raw")) { IOUtils.copy(makeInputStream(), new FileOutputStream(f)); } else { AudioSystem.write(makeStream(), t, f); } }
Code Sample 2:
public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
public boolean loadURL(URL url) { try { propertyBundle.load(url.openStream()); LOG.info("Configuration loaded from " + url + "\n"); return true; } catch (Exception e) { if (canComplain) { LOG.warn("Unable to load configuration " + url + "\n"); } canComplain = false; return false; } }
Code Sample 2:
protected boolean store(Context context) throws DataStoreException, ServletException { Connection db = context.getConnection(); Statement st = null; String q = null; Integer subscriber = context.getValueAsInteger("subscriber"); int amount = 0; if (subscriber == null) { throw new DataAuthException("Don't know who moderator is"); } Object response = context.get("Response"); if (response == null) { throw new DataStoreException("Don't know what to moderate"); } else { Context scratch = (Context) context.clone(); TableDescriptor.getDescriptor("response", "response", scratch).fetch(scratch); Integer author = scratch.getValueAsInteger("author"); if (subscriber.equals(author)) { throw new SelfModerationException("You may not moderate your own responses"); } } context.put("moderator", subscriber); context.put("moderated", response); if (db != null) { try { st = db.createStatement(); q = "select mods from subscriber where subscriber = " + subscriber.toString(); ResultSet r = st.executeQuery(q); if (r.next()) { if (r.getInt("mods") < 1) { throw new DataAuthException("You have no moderation points left"); } } else { throw new DataAuthException("Don't know who moderator is"); } Object reason = context.get("reason"); q = "select score from modreason where modreason = " + reason; r = st.executeQuery(q); if (r.next()) { amount = r.getInt("score"); context.put("amount", new Integer(amount)); } else { throw new DataStoreException("Don't recognise reason (" + reason + ") to moderate"); } context.put(keyField, null); if (super.store(context, db)) { db.setAutoCommit(false); q = "update RESPONSE set Moderation = " + "( select sum( Amount) from MODERATION " + "where Moderated = " + response + ") " + "where Response = " + response; st.executeUpdate(q); q = "update subscriber set mods = mods - 1 " + "where subscriber = " + subscriber; st.executeUpdate(q); q = "select author from response " + "where response = " + response; r = st.executeQuery(q); if (r.next()) { int author = r.getInt("author"); if (author != 0) { int points = -1; if (amount > 0) { points = 1; } StringBuffer qb = new StringBuffer("update subscriber "); qb.append("set score = score + ").append(amount); qb.append(", mods = mods + ").append(points); qb.append(" where subscriber = ").append(author); st.executeUpdate(qb.toString()); } } db.commit(); } } catch (Exception e) { try { db.rollback(); } catch (Exception whoops) { throw new DataStoreException("Shouldn't happen: " + "failed to back out " + "failed insert: " + whoops.getMessage()); } throw new DataStoreException("Failed to store moderation: " + e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (Exception noclose) { } context.releaseConnection(db); } } } return true; }
|
00
|
Code Sample 1:
private void getDirectories() throws IOException { if (user == null || ukey == null) { System.out.println("user and or ukey null"); } if (directories != null) { if (directories.length != 0) { System.out.println("directories already present"); return; } } HttpPost requestdirectories = new HttpPost(GET_DIRECTORIES_KEY_URL + "?ukey=" + ukey.getValue() + "&user=" + user.getValue()); HttpResponse dirResponse = getHttpClient().execute(requestdirectories); String ds = EntityUtils.toString(dirResponse.getEntity()); dirResponse.getEntity().consumeContent(); getDirectories(ds); }
Code Sample 2:
@Override public void run() { log.debug("Now running...."); log.debug("Current env. variables:"); try { this.infoNotifiers("Environment parameters after modifications:"); this.logEnvironment(); this.infoNotifiers("Dump thread will now run..."); this.endNotifiers(); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } List<String> cmd = new LinkedList<String>(); cmd.add("gzip"); cmd.add(info.getDumpFileName()); File basePath = this.pb.directory(); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } info.setDumpFileName(info.getDumpFileName() + ".gz"); info.setMD5SumFileName(info.getDumpFileName() + ".md5sum"); cmd = new LinkedList<String>(); cmd.add("md5sum"); cmd.add("-b"); cmd.add(info.getDumpFileName()); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); this.process = this.pb.start(); BufferedOutputStream md5sumFileOut = new BufferedOutputStream(new FileOutputStream(basePath.getAbsolutePath() + File.separatorChar + info.getMD5SumFileName())); IOUtils.copy(this.process.getInputStream(), md5sumFileOut); this.process.waitFor(); md5sumFileOut.flush(); md5sumFileOut.close(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip MD5Sum Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } else { this.startNotifiers(); this.infoNotifiers("Dump, gzip and md5sum sucessfuly completed."); this.endNotifiers(); } } catch (IOException e) { String message = "IOException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (InterruptedException e) { String message = "InterruptedException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (IntegrationException e) { String message = "IntegrationException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } }
|
11
|
Code Sample 1:
public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } }
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"); } }
|
00
|
Code Sample 1:
public static String getMd5Password(final String password) { String response = null; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = buffer.toString(); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
Code Sample 2:
public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
|
00
|
Code Sample 1:
protected void setupService(MessageContext msgContext) throws Exception { String realpath = msgContext.getStrProp(Constants.MC_REALPATH); String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION); if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION; if ((realpath != null) && (realpath.endsWith(extension))) { String jwsFile = realpath; String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); File f2 = new File(jwsFile); if (!f2.exists()) { throw new FileNotFoundException(rel); } if (rel.charAt(0) == '/') { rel = rel.substring(1); } int lastSlash = rel.lastIndexOf('/'); String dir = null; if (lastSlash > 0) { dir = rel.substring(0, lastSlash); } String file = rel.substring(lastSlash + 1); String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR); if (outdir == null) outdir = "."; if (dir != null) { outdir = outdir + File.separator + dir; } File outDirectory = new File(outdir); if (!outDirectory.exists()) { outDirectory.mkdirs(); } if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile); String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "java"; String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "class"; if (log.isDebugEnabled()) { log.debug("jFile: " + jFile); log.debug("cFile: " + cFile); log.debug("outdir: " + outdir); } File f1 = new File(cFile); String clsName = null; if (clsName == null) clsName = f2.getName(); if (clsName != null && clsName.charAt(0) == '/') clsName = clsName.substring(1); clsName = clsName.substring(0, clsName.length() - extension.length()); clsName = clsName.replace('/', '.'); if (log.isDebugEnabled()) log.debug("ClsName: " + clsName); if (!f1.exists() || f2.lastModified() > f1.lastModified()) { log.debug(Messages.getMessage("compiling00", jwsFile)); log.debug(Messages.getMessage("copy00", jwsFile, jFile)); FileReader fr = new FileReader(jwsFile); FileWriter fw = new FileWriter(jFile); char[] buf = new char[4096]; int rc; while ((rc = fr.read(buf, 0, 4095)) >= 0) fw.write(buf, 0, rc); fw.close(); fr.close(); log.debug("javac " + jFile); Compiler compiler = CompilerFactory.getCompiler(); compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext)); compiler.setDestination(outdir); compiler.addFile(jFile); boolean result = compiler.compile(); (new File(jFile)).delete(); if (!result) { (new File(cFile)).delete(); Document doc = XMLUtils.newDocument(); Element root = doc.createElementNS("", "Errors"); StringBuffer message = new StringBuffer("Error compiling "); message.append(jFile); message.append(":\n"); List errors = compiler.getErrors(); int count = errors.size(); for (int i = 0; i < count; i++) { CompilerError error = (CompilerError) errors.get(i); if (i > 0) message.append("\n"); message.append("Line "); message.append(error.getStartLine()); message.append(", column "); message.append(error.getStartColumn()); message.append(": "); message.append(error.getMessage()); } root.appendChild(doc.createTextNode(message.toString())); throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root }); } ClassUtils.removeClassLoader(clsName); soapServices.remove(clsName); } ClassLoader cl = ClassUtils.getClassLoader(clsName); if (cl == null) { cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile); } msgContext.setClassLoader(cl); SOAPService rpc = (SOAPService) soapServices.get(clsName); if (rpc == null) { rpc = new SOAPService(new RPCProvider()); rpc.setName(clsName); rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName); rpc.setEngine(msgContext.getAxisEngine()); String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS); if (allowed == null) allowed = "*"; rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed); String scope = (String) getOption(RPCProvider.OPTION_SCOPE); if (scope == null) scope = Scope.DEFAULT.getName(); rpc.setOption(RPCProvider.OPTION_SCOPE, scope); rpc.getInitializedServiceDesc(msgContext); soapServices.put(clsName, rpc); } rpc.setEngine(msgContext.getAxisEngine()); rpc.init(); msgContext.setService(rpc); } if (log.isDebugEnabled()) { log.debug("Exit: JWSHandler::invoke"); } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
11
|
Code Sample 1:
public static void copy(File in, File out) throws IOException { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
Code Sample 2:
public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
private int resourceToString(String aFile, StringBuffer aBuffer) { int cols = 0; URL url = getClass().getResource(aFile); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; do { line = in.readLine(); if (line != null) { if (line.length() > cols) cols = line.length(); aBuffer.append(line); aBuffer.append('\n'); } } while (line != null); } catch (IOException e) { e.printStackTrace(); } return cols; }
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 void rewrite(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new FileInputStream(args[0])); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); CodeAttribute attribute = method.getCodeAttribute(); int origStack = attribute.getMaxStack(); System.out.print(method.getName()); attribute.codeCheck(); System.out.println(" " + origStack + " " + attribute.getMaxStack()); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
Code Sample 2:
private void channelCopy(File source, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
|
11
|
Code Sample 1:
public void copyFilesIntoProject(HashMap<String, String> files) { Set<String> filenames = files.keySet(); for (String key : filenames) { String realPath = files.get(key); if (key.equals("fw4ex.xml")) { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + bundle.getString("Stem") + STEM_FILE_EXETENSION)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } else { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + key)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } } }
Code Sample 2:
public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
|
00
|
Code Sample 1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
Code Sample 2:
@Override public boolean exists() { if (local_file.exists()) { return true; } else { try { URLConnection c = remote_url.openConnection(); try { c.setConnectTimeout(CIO.getLoadingTimeOut()); c.connect(); return c.getContentLength() > 0; } catch (Exception err) { err.printStackTrace(); return false; } finally { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).disconnect(); } } } catch (IOException e) { e.printStackTrace(); return false; } } }
|
11
|
Code Sample 1:
public static void main(final String[] args) throws RecognitionException, TokenStreamException, IOException, IllegalOptionValueException, UnknownOptionException { try { CmdLineParser cmdLineParser = new CmdLineParser(); Option formatOption = cmdLineParser.addStringOption('f', "format"); Option encodingOption = cmdLineParser.addStringOption('c', "charset"); cmdLineParser.parse(args); String format = (String) cmdLineParser.getOptionValue(formatOption); String encoding = (String) cmdLineParser.getOptionValue(encodingOption); if (encoding == null || encoding.trim().equals("")) { encoding = "utf-8"; System.out.println("Defaulting to output charset utf-8 as argument -c is missing or not valid."); } String[] remainingArgs = cmdLineParser.getRemainingArgs(); if (remainingArgs.length != 2) { printUsage("Input and output file are not specified correctly. "); } File inputFile = new File(remainingArgs[0]); if (!inputFile.exists()) { printUsage("Input file " + remainingArgs[0] + " does not exist. "); } File outputFile = new File(remainingArgs[1]); if (!outputFile.exists()) { outputFile.createNewFile(); } if (format == null || format.trim().equals("")) { format = (String) FileUtil.cutExtension(outputFile.getName()).getValue(); } if ("tex".equals(format)) { Reader reader = new LatexEncoderReader(new FileReader(inputFile)); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outputFile), encoding); char[] buffer = new char[1024]; int read; do { read = reader.read(buffer); if (read > 0) { out.write(buffer, 0, read); } } while (read != -1); out.flush(); out.close(); } else { printUsage("Format not specified via argument -f. Also guessing for the extension of output file " + outputFile.getName() + " failed"); } } catch (Exception ex) { ex.printStackTrace(); printUsage(ex.getMessage()); } }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
|
00
|
Code Sample 1:
public static String getDocumentAsString(URL url) throws IOException { StringBuffer result = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8")); String line = ""; while (line != null) { result.append(line); line = in.readLine(); } return result.toString(); }
Code Sample 2:
public static String digest(String password) { try { byte[] digest; synchronized (__md5Lock) { if (__md == null) { try { __md = MessageDigest.getInstance("MD5"); } catch (Exception e) { Log.warn(e); return null; } } __md.reset(); __md.update(password.getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) { Log.warn(e); return null; } }
|
11
|
Code Sample 1:
public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
Code Sample 2:
public void test1() throws Exception { String senha = "minhaSenha"; MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(senha.getBytes()); byte[] bytes = digest.digest(); BASE64Encoder encoder = new BASE64Encoder(); String senhaCodificada = encoder.encode(bytes); System.out.println("Senha : " + senha); System.out.println("Senha SHA1: " + senhaCodificada); }
|
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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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 RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
|
11
|
Code Sample 1:
public static void loadConfig(DeviceEntry defaultDevice, EmulatorContext emulatorContext) { Config.defaultDevice = defaultDevice; Config.emulatorContext = emulatorContext; File configFile = new File(getConfigPath(), "config2.xml"); try { if (configFile.exists()) { loadConfigFile("config2.xml"); } else { configFile = new File(getConfigPath(), "config.xml"); if (configFile.exists()) { loadConfigFile("config.xml"); for (Enumeration e = getDeviceEntries().elements(); e.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) e.nextElement(); if (!entry.canRemove()) { continue; } removeDeviceEntry(entry); File src = new File(getConfigPath(), entry.getFileName()); File dst = File.createTempFile("dev", ".jar", getConfigPath()); IOUtils.copyFile(src, dst); entry.setFileName(dst.getName()); addDeviceEntry(entry); } } else { createDefaultConfigXml(); } saveConfig(); } } catch (IOException ex) { Logger.error(ex); createDefaultConfigXml(); } finally { if (configXml == null) { createDefaultConfigXml(); } } urlsMRU.read(configXml.getChildOrNew("files").getChildOrNew("recent")); initSystemProperties(); }
Code Sample 2:
@Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); }
|
00
|
Code Sample 1:
public void testRedirectWithCookie() throws Exception { String host = "localhost"; int port = this.localServer.getServicePort(); this.localServer.register("*", new BasicRedirectService(host, port)); DefaultHttpClient client = new DefaultHttpClient(); CookieStore cookieStore = new BasicCookieStore(); client.setCookieStore(cookieStore); BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setDomain("localhost"); cookie.setPath("/"); cookieStore.addCookie(cookie); HttpContext context = new BasicHttpContext(); HttpGet httpget = new HttpGet("/oldlocation/"); HttpResponse response = client.execute(getServerHttp(), httpget, context); HttpEntity e = response.getEntity(); if (e != null) { e.consumeContent(); } HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); Header[] headers = reqWrapper.getHeaders(SM.COOKIE); assertEquals("There can only be one (cookie)", 1, headers.length); }
Code Sample 2:
public void addUserToRealm(final NewUser user) { try { connection.setAutoCommit(false); final String pass, salt; final List<RealmWithEncryptedPass> realmPass = new ArrayList<RealmWithEncryptedPass>(); Realm realm; String username; username = user.username.toLowerCase(locale); PasswordHasher ph = PasswordFactory.getInstance().getPasswordHasher(); pass = ph.hashPassword(user.password); salt = ph.getSalt(); realmPass.add(new RealmWithEncryptedPass(cm.getRealm("null"), PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, "", user.password))); if (user.realms != null) { for (String realmName : user.realms) { realm = cm.getRealm(realmName); realmPass.add(new RealmWithEncryptedPass(realm, PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, realm.getFullRealmName(), user.password))); } user.realms = null; } new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.updatePassword")); psImpl.setString(1, pass); psImpl.setString(2, salt); psImpl.setInt(3, user.userId); psImpl.executeUpdate(); } }); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.addUser")); RealmWithEncryptedPass rwep; RealmDb realm; Iterator<RealmWithEncryptedPass> iter1 = realmPass.iterator(); while (iter1.hasNext()) { rwep = iter1.next(); realm = (RealmDb) rwep.realm; psImpl.setInt(1, realm.getRealmId()); psImpl.setInt(2, user.userId); psImpl.setInt(3, user.domainId); psImpl.setString(4, rwep.password); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUser(user.userId); } catch (GeneralSecurityException e) { log.error(e); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } throw new RuntimeException("Error updating Realms. Unable to continue Operation."); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
|
11
|
Code Sample 1:
private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); }
Code Sample 2:
public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File(destination); if (destinationFile.exists()) { destinationFile.delete(); } sourceStream = new BufferedInputStream(new FileInputStream(source)); destStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); int readByte; while ((readByte = sourceStream.read()) > 0) { destStream.write(readByte); } Object[] arg = { destinationFile.getName() }; String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg); LOG.fine(msg); } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } finally { try { if (destStream != null) { destStream.close(); } if (sourceStream != null) { sourceStream.close(); } } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } } }
|
11
|
Code Sample 1:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } }
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 int numberofLines(JApplet ja, String filename) { int count = 0; URL url = null; String FileToRead; FileToRead = "data/" + filename + ".csv"; try { url = new URL(ja.getCodeBase(), FileToRead); } catch (MalformedURLException e) { System.out.println("Malformed URL "); ja.stop(); } System.out.println(url.toString()); try { InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while ((reader.readLine()) != null) { count++; } in.close(); } catch (IOException e) { } return count; }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
11
|
Code Sample 1:
private void copyFile(String sourceFilename, String destDirname) throws BuildException { log("Copying file " + sourceFilename + " to " + destDirname); File destFile = getDestFile(sourceFilename, destDirname); InputStream inStream = null; OutputStream outStream = null; try { inStream = new BufferedInputStream(new FileInputStream(sourceFilename)); outStream = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] buffer = new byte[1024]; int n = 0; while ((n = inStream.read(buffer)) != -1) outStream.write(buffer, 0, n); } catch (Exception e) { throw new BuildException("Failed to copy file \"" + sourceFilename + "\" to directory \"" + destDirname + "\""); } finally { try { if (inStream != null) inStream.close(); } catch (IOException e) { } try { if (outStream != null) outStream.close(); } catch (IOException e) { } } }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void copyFile(String fromPath, String toPath) { try { File inputFile = new File(fromPath); String dirImg = (new File(toPath)).getParent(); File tmp = new File(dirImg); if (!tmp.exists()) { tmp.mkdir(); } File outputFile = new File(toPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); } }
|
11
|
Code Sample 1:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
private void copyFile(File source, File destination) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(destination); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int readCount = 0; while ((readCount = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, readCount); } } finally { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
|
11
|
Code Sample 1:
private String getCoded(String pass) { String passSecret = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(pass.getBytes("UTF8")); byte s[] = m.digest(); for (int i = 0; i < s.length; i++) { passSecret += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return passSecret; }
Code Sample 2:
public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } }
|
11
|
Code Sample 1:
@Test public void testCopy_inputStreamToOutputStream_IO84() throws Exception { long size = (long) Integer.MAX_VALUE + (long) 1; InputStream in = new NullInputStreamTest(size); OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { } @Override public void write(byte[] b) throws IOException { } @Override public void write(byte[] b, int off, int len) throws IOException { } }; assertEquals(-1, IOUtils.copy(in, out)); in.close(); assertEquals("copyLarge()", size, IOUtils.copyLarge(in, out)); }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
00
|
Code Sample 1:
public static void v2ljastaVeebileht(String s) throws IOException { URL url = new URL(s); InputStream is = url.openConnection().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } }
Code Sample 2:
public void loadFromInternet(boolean reload) { if (!reload && this.internetScoreGroupModel != null) { return; } loadingFlag = true; ProgressBar settingProgressBar = (ProgressBar) this.activity.findViewById(R.id.settingProgressBar); settingProgressBar.setVisibility(View.VISIBLE); final Timer timer = new Timer(); final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (loadingFlag == false) { ProgressBar settingProgressBar = (ProgressBar) BestScoreExpandableListAdapter.this.activity.findViewById(R.id.settingProgressBar); settingProgressBar.setVisibility(View.INVISIBLE); timer.cancel(); } super.handleMessage(msg); } }; final TimerTask task = new TimerTask() { @Override public void run() { Message message = new Message(); handler.sendMessage(message); } }; timer.schedule(task, 1, 50); String httpUrl = Constants.SERVER_URL + "/rollingcard.php?op=viewbestscore"; HttpGet request = new HttpGet(httpUrl); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String entity = EntityUtils.toString(response.getEntity()); String[] itemArray = entity.split(";"); this.internetScoreGroupModel = new ScoreGroupModel(); for (int i = 0; i < itemArray.length; i++) { String[] itemValueArray = itemArray[i].split("\\|"); if (itemValueArray.length != 3) { continue; } ScoreItemModel itemModel = new ScoreItemModel(itemValueArray[0], itemValueArray[1], itemValueArray[2]); this.internetScoreGroupModel.addItem(itemModel); } } } catch (ClientProtocolException e) { this.internetScoreGroupModel = null; e.printStackTrace(); } catch (IOException e) { this.internetScoreGroupModel = null; e.printStackTrace(); } loadingFlag = false; }
|
00
|
Code Sample 1:
public void loadProperties() { try { java.util.Properties props = new java.util.Properties(); java.net.URL url = ClassLoader.getSystemResource("env.properties"); props.load(url.openStream()); this.proxyCertificatePath = props.getProperty("proxy.certificate.path"); this.dummyFileDirName = props.getProperty("delete.dummyFileDirName"); this.idleTimeTestDelay = new Integer(props.getProperty("idleTimeTestDelaySeconds")); if (props.getProperty("gridftp.timeoutMilliSecs") != null) { this.gridftpTimeoutMilliSecs = new Integer(props.getProperty("gridftp.timeoutMilliSecs").trim()); } this.assertContentInWriteTests = new Boolean(props.getProperty("assertContentInWriteTests")); this.gridftpHost1 = props.getProperty("gridftp.host1"); this.gridftpPort1 = new Integer(props.getProperty("gridftp.port1")); this.gridftpHost2 = props.getProperty("gridftp.host2"); this.gridftpPort2 = new Integer(props.getProperty("gridftp.port2")); this.srbGsiHost = props.getProperty("srb.gsi.host"); this.srbGsiPort = new Integer(props.getProperty("srb.gsi.port")); this.srbGsiPortMin = new Integer(props.getProperty("srb.gsi.port.min")); this.srbGsiPortMax = new Integer(props.getProperty("srb.gsi.port.max")); this.srbGsiDefaultResource = props.getProperty("srb.gsi.defaultResource"); this.srbEncryptHost = props.getProperty("srb.encrypt.host"); this.srbEncryptPort = new Integer(props.getProperty("srb.encrypt.port")); this.srbEncryptPortMin = new Integer(props.getProperty("srb.encrypt.port.min")); this.srbEncryptPortMax = new Integer(props.getProperty("srb.encrypt.port.max")); this.srbEncryptDefaultResource = props.getProperty("srb.encrypt.defaultResource"); this.srbEncryptHomeDirectory = props.getProperty("srb.encrypt.homeDirectory"); this.srbEncryptMcatZone = props.getProperty("srb.encrypt.mcatZone"); this.srbEncryptMdasDomainName = props.getProperty("srb.encrypt.mdasDomainName"); this.srbEncryptUsername = props.getProperty("srb.encrypt.username"); this.srbEncryptPassword = props.getProperty("srb.encrypt.password"); this.sftpHost = props.getProperty("sftp.host"); this.sftpPort = new Integer(props.getProperty("sftp.port")); this.sftpPath = props.getProperty("sftp.path"); this.sftpUsername = props.getProperty("sftp.username"); this.sftpPassword = props.getProperty("sftp.password"); if (props.getProperty("sftp.timeoutMilliSecs") != null) { this.sftpTimeoutMilliSecs = new Integer(props.getProperty("sftp.timeoutMilliSecs").trim()); } irodsEncryptHost = props.getProperty("irods.encrypt.host"); irodsEncryptPort = new Integer(props.getProperty("irods.encrypt.port")); irodsEncryptResource = props.getProperty("irods.encrypt.defaultResource"); irodsEncryptHomeDirectory = props.getProperty("irods.encrypt.homeDirectory"); irodsEncryptZone = props.getProperty("irods.encrypt.zone"); irodsEncryptUsername = props.getProperty("irods.encrypt.username"); irodsEncryptPassword = props.getProperty("irods.encrypt.password"); irodsGsiHost = props.getProperty("irods.gsi.host"); irodsGsiPort = new Integer(props.getProperty("irods.gsi.port")); irodsGsiZone = props.getProperty("irods.gsi.zone"); srbQueryTimeout = new Integer(props.getProperty("srb.query.timeout")); this.ftpUri = props.getProperty("ftp.uri"); this.httpUri = props.getProperty("http.uri"); this.httpProxy = props.getProperty("http.proxy"); this.httpPort = new Integer(props.getProperty("http.port")); this.fileUri = props.getProperty("file.uri"); java.net.URI tempUri = new java.net.URI(this.fileUri); File f = new File(tempUri); if (!f.exists()) { String temp = System.getProperty("java.io.tmpdir"); System.out.println("Cannot list [" + fileUri + "] listing java.io.tmpdir instead [" + temp + "]"); this.fileUri = temp; } useSrbGsiInFsCopyTest = new Boolean(props.getProperty("srb.gsi.use.in.fs.copy.test")); useSrbEncryptInFsCopyTest = new Boolean(props.getProperty("srb.encrypt.use.in.fs.copy.test")); useGridftpHost1InFsCopyTest = new Boolean(props.getProperty("gridftp.host1.use.in.fs.copy.test")); useGridftpHost2InFsCopyTest = new Boolean(props.getProperty("gridftp.host2.use.in.fs.copy.test")); useSftpInFsCopyTest = new Boolean(props.getProperty("sftp.use.in.fs.copy.test")); useLocalFileInFsCopyTest = new Boolean(props.getProperty("file.use.in.fs.copy.test")); useIrodsGsiCopyTest = new Boolean(props.getProperty("irods.gsi.use.in.fs.copy.test")); useIrodsEncryptCopyTest = new Boolean(props.getProperty("irods.encrypt.use.in.fs.copy.test")); assertNotNull(this.proxyCertificatePath); assertNotNull(this.dummyFileDirName); assertNotNull(this.idleTimeTestDelay); assertNotNull(this.ftpUri); assertNotNull(this.httpUri); } catch (Exception ex) { Logger.getLogger(AbstractTestClass.class.getName()).log(Level.SEVERE, null, ex); fail("Unable to locate and load 'testsettings.properties' file in source " + ex); } }
Code Sample 2:
private void LoadLoginInfo() { m_PwdList.removeAllElements(); String szTemp = null; int iIndex = 0; int iSize = m_UsrList.size(); for (int i = 0; i < iSize; i++) m_PwdList.add(""); try { if ((m_UsrList.size() > 0) && m_bSavePwd) { char[] MD5PWD = new char[80]; java.util.Arrays.fill(MD5PWD, (char) 0); java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-1"); String szPath = System.getProperty("user.home"); szPath += System.getProperty("file.separator") + "MochaJournal" + System.getProperty("file.separator") + "user.dat"; java.io.File file = new java.io.File(szPath); if (file.exists()) { java.io.FileInputStream br = new java.io.FileInputStream(file); byte[] szEncryptPwd = null; int iLine = 0; while (br.available() > 0) { md.reset(); md.update(((String) m_UsrList.get(iLine)).getBytes()); byte[] DESUSR = md.digest(); byte alpha = 0; for (int i2 = 0; i2 < DESUSR.length; i2++) alpha += DESUSR[i2]; iSize = br.read(); if (iSize > 0) { szEncryptPwd = new byte[iSize]; br.read(szEncryptPwd); char[] cPwd = new char[iSize]; for (int i = 0; i < iSize; i++) { int iChar = (int) szEncryptPwd[i] - (int) alpha; if (iChar < 0) iChar += 256; cPwd[i] = (char) iChar; } m_PwdList.setElementAt(new String(cPwd), iLine); } iLine++; } } } } catch (java.security.NoSuchAlgorithmException e) { System.err.println(e); } catch (java.io.IOException e3) { System.err.println(e3); } }
|
11
|
Code Sample 1:
public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); int hashLength = hash.length; StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { System.out.println("Error getting password hash - " + nsae.getMessage()); return null; } }
Code Sample 2:
public void setPassword(UserType user, String clearPassword) { try { Random r = new Random(); String newSalt = Long.toString(Math.abs(r.nextLong())); MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(newSalt.getBytes("UTF-8")); md.update(clearPassword.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); user.setPassword(encodedString); user.setSalt(newSalt); this.markModified(user); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(errorMessage, ex); GlobalUITools.displayFatalExceptionMessage(null, errorMessage, ex, true); } }
|
11
|
Code Sample 1:
public void genCreateSchema(DiagramModel diagramModel, String source) { try { con.setAutoCommit(false); stmt = con.createStatement(); Collection boxes = diagramModel.getBoxes(); BoxModel box; ItemModel item; String sqlQuery; int counter = 0; for (Iterator x = boxes.iterator(); x.hasNext(); ) { box = (BoxModel) x.next(); if (!box.isAbstractDef()) { sqlQuery = sqlCreateTableBegin(box); Collection items = box.getItems(); for (Iterator y = items.iterator(); y.hasNext(); ) { item = (ItemModel) y.next(); sqlQuery = sqlQuery + sqlColumn(item); } sqlQuery = sqlQuery + sqlForeignKeyColumns(box); sqlQuery = sqlQuery + sqlPrimaryKey(box); sqlQuery = sqlQuery + sqlUniqueKey(box); sqlQuery = sqlQuery + sqlCreateTableEnd(box, source); System.out.println(sqlQuery); try { stmt.executeUpdate(sqlQuery); counter++; } catch (SQLException e) { String tableName = box.getName(); System.out.println("// Problem while creating table " + tableName + " : " + e.getMessage()); String msg = Para.getPara().getText("tableNotCreated") + " -- " + tableName; this.informUser(msg); } } } this.genCreateForeignKeys(diagramModel); con.commit(); if (counter > 0) { String msg = Para.getPara().getText("schemaCreated") + " -- " + counter + " " + Para.getPara().getText("tables"); this.informUser(msg); } else { this.informUser(Para.getPara().getText("schemaNotCreated")); } } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the JDBC schema generation! "); try { con.rollback(); this.informUser(Para.getPara().getText("schemaNotCreated")); } catch (SQLException e1) { System.out.println(e1.getMessage() + " // Problem with the connection rollback! "); } } finally { try { con.setAutoCommit(true); stmt.close(); } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the statement closing! "); } } }
Code Sample 2:
@Test public void test00_reinitData() throws Exception { Logs.logMethodName(); init(); Db db = DbConnection.defaultCieDbRW(); try { db.begin(); PreparedStatement pst = db.prepareStatement("TRUNCATE e_module;"); pst.executeUpdate(); pst = db.prepareStatement("TRUNCATE e_application_version;"); pst.executeUpdate(); ModuleHelper.synchronizeDbWithModuleList(db); ModuleHelper.declareNewVersion(db); ModuleHelper.updateModuleVersions(db); esisId = com.entelience.directory.PeopleFactory.lookupUserName(db, "esis"); assertNotNull(esisId); guestId = com.entelience.directory.PeopleFactory.lookupUserName(db, "guest"); assertNotNull(guestId); extenId = com.entelience.directory.PeopleFactory.lookupUserName(db, "exten"); assertNotNull(extenId); db.commit(); } catch (Exception e) { db.rollback(); throw e; } }
|
00
|
Code Sample 1:
public Leilao insertLeilao(Leilao leilao) throws SQLException { Connection conn = null; String insert = "insert into Leilao (idleilao, atividade_idatividade, datainicio, datafim) " + "values " + "(nextval('seq_leilao'), " + leilao.getAtividade().getIdAtividade() + ", '" + leilao.getDataInicio() + "', '" + leilao.getDataFim() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_leilao"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { leilao.setIdLeilao(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
Code Sample 2:
public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
|
11
|
Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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 void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void triggerBuild(Properties props, String project, int rev) throws IOException { boolean doBld = Boolean.parseBoolean(props.getProperty(project + ".bld")); String url = props.getProperty(project + ".url"); if (!doBld || project == null || project.length() == 0) { System.out.println("BuildLauncher: Not configured to build '" + project + "'"); return; } else if (url == null) { throw new IOException("Tried to launch build for project '" + project + "' but " + project + ".url property is not defined!"); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); System.out.println(fmt.format(new Date()) + ": Triggering a build via: " + url); BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while (r.readLine() != null) ; System.out.println(fmt.format(new Date()) + ": Build triggered!"); LATEST_BUILD.put(project, rev); r.close(); System.out.println(fmt.format(new Date()) + ": triggerBuild() done!"); }
Code Sample 2:
private String getData(String method, String arg) { try { URL url; String str; StringBuilder strBuilder; BufferedReader stream; url = new URL(API_BASE_URL + "/2.1/" + method + "/en/xml/" + API_KEY + "/" + URLEncoder.encode(arg, "UTF-8")); stream = new BufferedReader(new InputStreamReader(url.openStream())); strBuilder = new StringBuilder(); while ((str = stream.readLine()) != null) { strBuilder.append(str); } stream.close(); return strBuilder.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
|
00
|
Code Sample 1:
public void run() { FTPClient ftp = null; try { StarkHhDownloaderEtcProperties etcProperties = new StarkHhDownloaderEtcProperties(getUri()); StarkHhDownloaderVarProperties varProperties = new StarkHhDownloaderVarProperties(getUri()); ftp = new FTPClient(); int reply; ftp.connect(etcProperties.getHostname()); log("Connecting to ftp server at " + etcProperties.getHostname() + "."); log("Server replied with '" + ftp.getReplyString() + "'."); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw UserException.newOk("FTP server refused connection."); } log("Connected to server, now logging in."); ftp.login(etcProperties.getUsername(), etcProperties.getPassword()); log("Server replied with '" + ftp.getReplyString() + "'."); List<String> directories = etcProperties.getDirectories(); for (int i = 0; i < directories.size(); i++) { log("Checking the directory '" + directories.get(i) + "'."); boolean found = false; FTPFile[] filesArray = ftp.listFiles(directories.get(i)); List<FTPFile> files = Arrays.asList(filesArray); Collections.sort(files, new Comparator<FTPFile>() { public int compare(FTPFile file1, FTPFile file2) { if (file2.getTimestamp().getTime().equals(file1.getTimestamp().getTime())) { return file2.getName().compareTo(file1.getName()); } else { return file1.getTimestamp().getTime().compareTo(file2.getTimestamp().getTime()); } } }); for (FTPFile file : files) { if (file.getType() == FTPFile.FILE_TYPE && (varProperties.getLastImportDate(i) == null ? true : (file.getTimestamp().getTime().equals(varProperties.getLastImportDate(i).getDate()) ? file.getName().compareTo(varProperties.getLastImportName(i)) < 0 : file.getTimestamp().getTime().after(varProperties.getLastImportDate(i).getDate())))) { String fileName = directories.get(i) + "\\" + file.getName(); if (file.getSize() == 0) { log("Ignoring '" + fileName + "'because it has zero length"); } else { log("Attempting to download '" + fileName + "'."); InputStream is = ftp.retrieveFileStream(fileName); if (is == null) { reply = ftp.getReplyCode(); throw UserException.newOk("Can't download the file '" + file.getName() + "', server says: " + reply + "."); } log("File stream obtained successfully."); hhImporter = new HhDataImportProcess(getContract().getId(), new Long(0), is, fileName + ".df2", file.getSize()); hhImporter.run(); List<VFMessage> messages = hhImporter.getMessages(); hhImporter = null; if (messages.size() > 0) { for (VFMessage message : messages) { log(message.getDescription()); } throw UserException.newInvalidParameter("Problem loading file."); } } if (!ftp.completePendingCommand()) { throw UserException.newOk("Couldn't complete ftp transaction: " + ftp.getReplyString()); } varProperties.setLastImportDate(i, new MonadDate(file.getTimestamp().getTime())); varProperties.setLastImportName(i, file.getName()); found = true; } } if (!found) { log("No new files found."); } } } catch (UserException e) { try { log(e.getVFMessage().getDescription()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (IOException e) { try { log(e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (Throwable e) { try { log("Exception: " + e.getClass().getName() + " Message: " + e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } ChellowLogger.getLogger().logp(Level.SEVERE, "ContextListener", "contextInitialized", "Can't initialize context.", e); } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); log("Logged out."); } catch (IOException ioe) { } catch (ProgrammerException e) { } catch (UserException e) { } } } }
Code Sample 2:
private static String makeMD5(String str) { byte[] bytes = new byte[32]; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes("iso-8859-1"), 0, str.length()); bytes = md.digest(); } catch (Exception e) { return null; } return convertToHex(bytes); }
|
11
|
Code Sample 1:
public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); byte[] hash = (new Base64()).encode(raw); return new String(hash); } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } }
Code Sample 2:
public static String hashString(String password) { String hashword = null; try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(password.getBytes("UTF-8")); BigInteger hash = new BigInteger(1, sha.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { log.error(nsae); } catch (UnsupportedEncodingException e) { log.error(e); } return pad(hashword, 32, '0'); }
|
11
|
Code Sample 1:
public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
|
11
|
Code Sample 1:
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(); } }
Code Sample 2:
public static void main(String[] args) throws IOException, DataFormatException { byte in_buf[] = new byte[20000]; if (args.length < 2) { System.out.println("too few arguments"); System.exit(0); } String inputName = args[0]; InputStream in = new FileInputStream(inputName); int index = 0; for (int i = 1; i < args.length; i++) { int size = Integer.parseInt(args[i]); boolean copy = size >= 0; if (size < 0) { size = -size; } OutputStream out = null; if (copy) { index++; out = new FileOutputStream(inputName + "." + index + ".dat"); } while (size > 0) { int read = in.read(in_buf, 0, Math.min(in_buf.length, size)); if (read < 0) { break; } size -= read; if (copy) { out.write(in_buf, 0, read); } } if (copy) { out.close(); } } index++; OutputStream out = new FileOutputStream(inputName + "." + index + ".dat"); while (true) { int read = in.read(in_buf); if (read < 0) { break; } out.write(in_buf, 0, read); } out.close(); in.close(); }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
private void checkResourceAvailable() throws XQException { HttpUriRequest head = new HttpHead(remoteURL); try { HttpResponse response = httpClient.execute(head); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw new XQException("Could not connect to the remote resource, response code: " + response.getStatusLine().getStatusCode() + " reason: " + response.getStatusLine().getReasonPhrase()); } catch (ClientProtocolException cpe) { throw new XQException(cpe.getMessage()); } catch (IOException ioe) { throw new XQException(ioe.getMessage()); } }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
11
|
Code Sample 1:
protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; }
Code Sample 2:
private static void loadFromZip() { InputStream in = Resources.class.getResourceAsStream("data.zip"); if (in == null) { return; } ZipInputStream zipIn = new ZipInputStream(in); try { while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String entryName = entry.getName(); if (!entryName.startsWith("/")) { entryName = "/" + entryName; } ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(zipIn, out); zipIn.closeEntry(); FILES.put(entryName, out.toByteArray()); } zipIn.close(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copyFile(File source, File target) throws Exception { if (source.isDirectory()) { if (!target.isDirectory()) { target.mkdirs(); } String[] children = source.list(); for (int i = 0; i < children.length; i++) { copyFile(new File(source, children[i]), new File(target, children[i])); } } else { FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(target).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { errorLog("{Malgn.copyFile} " + e.getMessage()); throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } }
Code Sample 2:
private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
|
00
|
Code Sample 1:
public static long download(String address, String localFileName) throws Exception { OutputStream out = null; URLConnection conn = null; InputStream in = null; long numWritten = 0; try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { System.out.println("Error: " + exception); throw exception; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } return numWritten; } }
Code Sample 2:
private void insert(Connection c) throws SQLException { if (m_fromDb) throw new IllegalStateException("The record already exists in the database"); StringBuffer names = new StringBuffer("INSERT INTO ifServices (nodeID,ipAddr,serviceID"); StringBuffer values = new StringBuffer("?,?,?"); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) { values.append(",?"); names.append(",ifIndex"); } if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) { values.append(",?"); names.append(",status"); } if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { values.append(",?"); names.append(",lastGood"); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { values.append(",?"); names.append(",lastFail"); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) { values.append(",?"); names.append(",source"); } if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) { values.append(",?"); names.append(",notify"); } if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) { values.append(",?"); names.append(",qualifier"); } names.append(") VALUES (").append(values).append(')'); if (log().isDebugEnabled()) log().debug("DbIfServiceEntry.insert: SQL insert statment = " + names.toString()); PreparedStatement stmt = null; PreparedStatement delStmt = null; final DBUtils d = new DBUtils(getClass()); try { stmt = c.prepareStatement(names.toString()); d.watch(stmt); names = null; int ndx = 1; stmt.setInt(ndx++, m_nodeId); stmt.setString(ndx++, m_ipAddr.getHostAddress()); stmt.setInt(ndx++, m_serviceId); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) stmt.setInt(ndx++, m_ifIndex); if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) stmt.setString(ndx++, new String(new char[] { m_status })); if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { stmt.setTimestamp(ndx++, m_lastGood); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { stmt.setTimestamp(ndx++, m_lastFail); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) stmt.setString(ndx++, new String(new char[] { m_source })); if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) stmt.setString(ndx++, new String(new char[] { m_notify })); if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) stmt.setString(ndx++, m_qualifier); int rc; try { rc = stmt.executeUpdate(); } catch (SQLException e) { log().warn("ifServices DB insert got exception; will retry after " + "deletion of any existing records for this ifService " + "that are marked for deletion.", e); c.rollback(); String delCmd = "DELETE FROM ifServices WHERE status = 'D' " + "AND nodeid = ? AND ipAddr = ? AND serviceID = ?"; delStmt = c.prepareStatement(delCmd); d.watch(delStmt); delStmt.setInt(1, m_nodeId); delStmt.setString(2, m_ipAddr.getHostAddress()); delStmt.setInt(3, m_serviceId); rc = delStmt.executeUpdate(); rc = stmt.executeUpdate(); } log().debug("insert(): SQL update result = " + rc); } finally { d.cleanUp(); } m_fromDb = true; m_changed = 0; }
|
11
|
Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } }
|
00
|
Code Sample 1:
public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) { log.info("Start update auth"); PreparedStatement ps = null; DatabaseAdapter db = null; try { db = DatabaseAdapter.getInstance(); String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE ID_AUTH_USER=? "; ps = db.prepareStatement(sql); if (infoAuth.getAuthInfo().getCompanyId() == null) { ps.setNull(1, Types.INTEGER); ps.setInt(2, 0); } else { ps.setLong(1, infoAuth.getAuthInfo().getCompanyId()); ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0); } if (infoAuth.getAuthInfo().getHoldingId() == null) { ps.setNull(3, Types.INTEGER); ps.setInt(4, 0); } else { ps.setLong(3, infoAuth.getAuthInfo().getHoldingId()); ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0); } ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId()); ps.executeUpdate(); processDeletedRoles(db, infoAuth); processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId()); db.commit(); } catch (Throwable e) { try { if (db != null) db.rollback(); } catch (Exception e001) { } final String es = "Error add user auth"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(db, ps); ps = null; db = null; log.info("End update auth"); } }
Code Sample 2:
public String getDigest(String algorithm, String data) throws IOException, NoSuchAlgorithmException { MessageDigest md = java.security.MessageDigest.getInstance(algorithm); md.reset(); md.update(data.getBytes()); return md.digest().toString(); }
|
00
|
Code Sample 1:
public int fileUpload(File pFile, String uploadName, Hashtable pValue) throws Exception { int res = 0; MultipartEntity reqEntity = new MultipartEntity(); if (uploadName != null) { FileBody bin = new FileBody(pFile); reqEntity.addPart(uploadName, bin); } Enumeration<String> enm = pValue.keys(); String key; while (enm.hasMoreElements()) { key = enm.nextElement(); reqEntity.addPart(key, new StringBody("" + pValue.get(key))); } httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); res = response.getStatusLine().getStatusCode(); close(); return res; }
Code Sample 2:
@Override public void excluir(Disciplina t) throws Exception { PreparedStatement stmt = null; String sql = "DELETE from disciplina where id_disciplina = ?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, t.getIdDisciplina()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } finally { try { stmt.close(); conexao.close(); } catch (SQLException e) { throw e; } } }
|
00
|
Code Sample 1:
public static String generateStringSHA256(String content) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ScannerChecksum.class.getName()).log(Level.SEVERE, null, ex); } md.update(content.getBytes()); byte byteData[] = md.digest(); @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
11
|
Code Sample 1:
public static String encryptPassword(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { LOG.error(e); } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e); } return (new BASE64Encoder()).encode(md.digest()); }
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(); }
|
11
|
Code Sample 1:
public static void _he3Decode(String in_file) { try { File out = new File(in_file + dec_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()); InputStreamReader inputReader = new InputStreamReader(in_stream, "ISO8859_1"); OutputStreamWriter outputWriter = new OutputStreamWriter(out_stream, "ISO8859_1"); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; char char_arr[] = new char[8]; int buff_size = char_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + dec_mode + ": " + in_file + "\n" + dec_mode + " to: " + in_file + dec_extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = inputReader.read(char_arr, 0, buff_size); if (_chars_read == -1) break; for (int i = 0; i < _chars_read; i++) byte_arr[i] = (byte) char_arr[i]; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\n" + dec_mode + ": "); outputWriter.write(new String(_decode((ByteArrayOutputStream) os), "ISO-8859-1")); 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()); } }
Code Sample 2:
public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); 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:
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
Code Sample 2:
private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) { MessageDigest md; byte[] temp_digest, pass_digest; byte[] hex_digest = new byte[35]; byte[] scrambled = scrambledPassword.getBytes(); try { md = MessageDigest.getInstance("MD5"); md.update(plainPassword.getBytes("US-ASCII")); md.update(user.getBytes("US-ASCII")); temp_digest = md.digest(); Utils.bytesToHex(temp_digest, hex_digest, 0); md.update(hex_digest, 0, 32); md.update(salt.getBytes()); pass_digest = md.digest(); Utils.bytesToHex(pass_digest, hex_digest, 3); hex_digest[0] = (byte) 'm'; hex_digest[1] = (byte) 'd'; hex_digest[2] = (byte) '5'; for (int i = 0; i < hex_digest.length; i++) { if (scrambled[i] != hex_digest[i]) { return false; } } } catch (Exception e) { logger.error(e); } return true; }
|
00
|
Code Sample 1:
public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
Code Sample 2:
private void storeFieldMap(WorkingContent c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); try { if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } finally { if (ps != null) ps.close(); } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } }
|
11
|
Code Sample 1:
private void simulate() throws Exception { BufferedWriter out = null; out = new BufferedWriter(new FileWriter(outFile)); out.write("#Thread\tReputation\tAction\n"); out.flush(); System.out.println("Simulate..."); File file = new File(trsDemoSimulationfile); ObtainUserReputation obtainUserReputationRequest = new ObtainUserReputation(); ObtainUserReputationResponse obtainUserReputationResponse; RateUser rateUserRequest; RateUserResponse rateUserResponse; FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String call = br.readLine(); while (call != null) { rateUserRequest = generateRateUserRequest(call); try { rateUserResponse = trsPort.rateUser(rateUserRequest); System.out.println("----------------R A T I N G-------------------"); System.out.println("VBE: " + rateUserRequest.getVbeId()); System.out.println("VO: " + rateUserRequest.getVoId()); System.out.println("USER: " + rateUserRequest.getUserId()); System.out.println("SERVICE: " + rateUserRequest.getServiceId()); System.out.println("ACTION: " + rateUserRequest.getActionId()); System.out.println("OUTCOME: " + rateUserResponse.isOutcome()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the rateUser should be true: MESSAGE=" + rateUserResponse.getMessage(), true, rateUserResponse.isOutcome()); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(null); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(rateUserRequest.getVoId()); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } call = br.readLine(); } fis.close(); br.close(); out.flush(); out.close(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&") != -1) { String syn1 = syn.substring(0, syn.indexOf("&")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } }
Code Sample 2:
public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
00
|
Code Sample 1:
public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.out.println("test"); URL url = new URL(addr); System.out.println("test2"); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public boolean write(Node node, LSOutput output) throws LSException { OutputStream out = output.getByteStream(); try { if (out == null) { String systemId = output.getSystemId(); try { URL url = new URL(systemId); URLConnection connection = url.openConnection(); connection.setDoOutput(true); if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setRequestMethod("PUT"); } out = connection.getOutputStream(); } catch (MalformedURLException e) { File file = new File(systemId); out = new FileOutputStream(file); } } serialize(node, out); out.flush(); return true; } catch (IOException e) { throw new DomLSException(LSException.SERIALIZE_ERR, e); } }
|
11
|
Code Sample 1:
private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); }
Code Sample 2:
public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
|
00
|
Code Sample 1:
private static QDataSet test3_binary() throws IOException, StreamException { URL url = TestQDataSetStreamHandler.class.getResource("test3.binary.qds"); QDataSetStreamHandler handler = new QDataSetStreamHandler(); StreamTool.readStream(Channels.newChannel(url.openStream()), handler); QDataSet qds = handler.getDataSet(); return qds; }
Code Sample 2:
public String retrieve(String url) { HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); if (getResponseEntity != null) { return EntityUtils.toString(getResponseEntity); } } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; }
|
00
|
Code Sample 1:
@HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
Code Sample 2:
protected String readUrl(String urlString) throws IOException { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String inputLine; while ((inputLine = in.readLine()) != null) response += inputLine; in.close(); return response; }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
String fetch_pls(String pls) { InputStream pstream = null; if (pls.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), pls); else url = new URL(pls); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + pls); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; if (line.startsWith("File1=")) { byte[] foo = line.getBytes(); int i = 6; for (; i < foo.length; i++) { if (foo[i] == 0x0d) break; } return line.substring(6, i); } } return null; }
|
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:
private static String readGeoJSON(String feature) { StringBuffer content = new StringBuffer(); try { URL url = new URL(feature); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { content.append(line); } conn.disconnect(); } catch (Exception e) { } return content.toString(); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFromOffset(long offset, File exe, File cab) throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(exe)); FileOutputStream out = new FileOutputStream(cab); byte[] buffer = new byte[4096]; int bytes_read; in.skipBytes((int) offset); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); in = null; out = null; }
|
11
|
Code Sample 1:
public static void main(String[] args) { try { URL url = new URL("http://www.lineadecodigo.com"); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (Throwable t) { } String inputLine; String inputText = ""; while ((inputLine = in.readLine()) != null) { inputText = inputText + inputLine; } System.out.println("El contenido de la URL es: " + inputText); in.close(); } catch (MalformedURLException me) { System.out.println("URL erronea"); } catch (IOException ioe) { System.out.println("Error IO"); } }
Code Sample 2:
private void checkForLatestVersion() { log(Color.BLUE, "Checking for latest version."); try { double LatestVersion = 0.0; URL url = new URL("http://www.powerbot.org/vb/showthread.php?t=723144"); URLConnection urlc = url.openConnection(); BufferedReader bf = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String CurrentLine; while ((CurrentLine = bf.readLine()) != null) { if (CurrentLine.contains("<pre class=\"bbcode_code\"style=\"height:48px;\"><i>Current version")) { for (String s : CurrentLine.split(" ")) { try { LatestVersion = Double.parseDouble(s); } catch (NumberFormatException nfe) { } } } } double CurrentVersion = getClass().getAnnotation(ScriptManifest.class).version(); String Message = LatestVersion < CurrentVersion ? ", you should update to the latest version!" : ", you have the latest version of this script."; log(LatestVersion < CurrentVersion ? Color.RED : Color.BLUE, "Latest version available : " + LatestVersion + Message); } catch (IOException ioe) { log(Color.RED, "Couldn't retreive latest version due to a connection issue!"); } catch (NumberFormatException nfe) { log(Color.RED, "Couldn't reveice latest version; no version were available on PowerBot website!."); } catch (Exception e) { log(Color.RED, "Couldn't retreive latest version due to an unknown reason!"); } }
|
11
|
Code Sample 1:
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } }
Code Sample 2:
private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static String callApi(String api, String paramname, String paramvalue) { String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/" + api, paramname, paramvalue); u = SSOUtil.addParameter(u, "servicekey", SSOFilter.getServicekey()); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } }
Code Sample 2:
public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; }
|
11
|
Code Sample 1:
@Override protected RequestLogHandler createRequestLogHandler() { try { File logbackConf = File.createTempFile("logback-access", ".xml"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("logback-access.xml"), new FileOutputStream(logbackConf)); RequestLogHandler requestLogHandler = new RequestLogHandler(); RequestLogImpl requestLog = new RequestLogImpl(); requestLog.setFileName(logbackConf.getPath()); requestLogHandler.setRequestLog(requestLog); } catch (FileNotFoundException e) { log.error("Could not create request log handler", e); } catch (IOException e) { log.error("Could not create request log handler", e); } return null; }
Code Sample 2:
public static void copyFile(File input, File output) throws Exception { FileReader in = new FileReader(input); FileWriter out = new FileWriter(output); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
@Override protected Drawing construct() throws IOException { Drawing result; System.out.println("getParameter.datafile:" + getParameter("datafile")); if (getParameter("data") != null) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data"))); result = (Drawing) domi.readObject(0); } else if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); InputStream in = url.openConnection().getInputStream(); try { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in); result = (Drawing) domi.readObject(0); } finally { in.close(); } } else { result = null; } return result; }
Code Sample 2:
public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
Code Sample 2:
public static void fileUpload() throws IOException { file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\ImageShackUploaderPlugin.java"); HttpPost httppost = new HttpPost(localhostrurl); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("name", new StringBody(file.getName())); if (login) { mpEntity.addPart("session", new StringBody(sessioncookie.substring(sessioncookie.indexOf("=") + 2))); } mpEntity.addPart("file", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into localhost..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { String tmp = EntityUtils.toString(resEntity); downloadlink = parseResponse(tmp, "\"url\":\"", "\""); System.out.println("download link : " + downloadlink); } }
|
11
|
Code Sample 1:
private static long copy(InputStream source, OutputStream sink) { try { return IOUtils.copyLarge(source, sink); } catch (IOException e) { throw new FaultException("System error copying stream", e); } finally { IOUtils.closeQuietly(source); IOUtils.closeQuietly(sink); } }
Code Sample 2:
public static void main(String[] args) { File directory = new File(args[0]); File[] files = directory.listFiles(); try { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1]))); for (int i = 0; i < files.length; i++) { BufferedReader reader = new BufferedReader(new FileReader(files[i])); while (reader.ready()) writer.println(reader.readLine()); reader.close(); } writer.flush(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: HashCalculator <Algorithm> <Input>"); System.out.println("The preferred algorithm is SHA."); } else { MessageDigest md; try { md = MessageDigest.getInstance(args[0]); md.update(args[1].getBytes()); System.out.print("Hashed value of " + args[1] + " is: "); System.out.println((new BASE64Encoder()).encode(md.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } }
Code Sample 2:
public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); }
|
11
|
Code Sample 1:
public boolean excuteBackup(String backupOrginlDrctry, String targetFileNm, String archiveFormat) throws JobExecutionException { File targetFile = new File(targetFileNm); File srcFile = new File(backupOrginlDrctry); if (!srcFile.exists()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); } if (srcFile.isFile()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); } boolean result = false; FileInputStream finput = null; FileOutputStream fosOutput = null; ArchiveOutputStream aosOutput = null; ArchiveEntry entry = null; try { log.debug("charter set : " + Charset.defaultCharset().name()); fosOutput = new FileOutputStream(targetFile); aosOutput = new ArchiveStreamFactory().createArchiveOutputStream(archiveFormat, fosOutput); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { ((TarArchiveOutputStream) aosOutput).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } File[] fileArr = srcFile.listFiles(); ArrayList list = EgovFileTool.getSubFilesByAll(fileArr); for (int i = 0; i < list.size(); i++) { File sfile = new File((String) list.get(i)); finput = new FileInputStream(sfile); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { entry = new TarArchiveEntry(sfile, new String(sfile.getAbsolutePath().getBytes(Charset.defaultCharset().name()), "8859_1")); ((TarArchiveEntry) entry).setSize(sfile.length()); } else { entry = new ZipArchiveEntry(sfile.getAbsolutePath()); ((ZipArchiveEntry) entry).setSize(sfile.length()); } aosOutput.putArchiveEntry(entry); IOUtils.copy(finput, aosOutput); aosOutput.closeArchiveEntry(); finput.close(); result = true; } aosOutput.close(); } catch (Exception e) { log.error("백업화일생성중 에러가 발생했습니다. 에러 : " + e.getMessage()); log.debug(e); result = false; throw new JobExecutionException("백업화일생성중 에러가 발생했습니다.", e); } finally { try { if (finput != null) finput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (aosOutput != null) aosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (fosOutput != null) fosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (result == false) targetFile.delete(); } catch (Exception e2) { log.error("IGNORE:", e2); } } return result; }
Code Sample 2:
private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
private void storeConfigurationPropertiesFile(java.net.URL url, String comp) { java.util.Properties p; try { p = new java.util.Properties(); p.load(url.openStream()); } catch (java.io.IOException ie) { System.err.println("error opening: " + url.getPath() + ": " + ie.getMessage()); return; } storeConfiguration(p, comp); return; }
Code Sample 2:
public FileInputStream execute() { FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); String pdfPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf"); try { FileOutputStream outputStream = new FileOutputStream(pdfPath + "/driveTogether.pdf"); PdfWriter writer = PdfWriter.getInstance(doc, outputStream); doc.open(); String pfad = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf/template.pdf"); logger.info("Loading PDF-Template: " + pfad); PdfReader reader = new PdfReader(pfad); PdfImportedPage page = writer.getImportedPage(reader, 1); PdfContentByte cb = writer.getDirectContent(); cb.addTemplate(page, 0, 0); doHeader(); doParagraph(trip, forUser); doc.close(); fis = new FileInputStream(pdfPath + "/driveTogether.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fis; }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel inputFileChannel = new FileInputStream(sourceFile).getChannel(); FileChannel outputFileChannel = new FileOutputStream(destFile).getChannel(); long offset = 0L; long length = inputFileChannel.size(); final long MAXTRANSFERBUFFERLENGTH = 1024 * 1024; try { for (; offset < length; ) { offset += inputFileChannel.transferTo(offset, MAXTRANSFERBUFFERLENGTH, outputFileChannel); inputFileChannel.position(offset); } } finally { try { outputFileChannel.close(); } catch (Exception ignore) { } try { inputFileChannel.close(); } catch (IOException ignore) { } } }
Code Sample 2:
public ResourceMigrator createDefaultResourceMigrator(NotificationReporter reporter, boolean strictMode) throws ResourceMigrationException { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; }
|
00
|
Code Sample 1:
public String getHtml(String path) throws Exception { URL url = new URL(path); URLConnection conn = url.openConnection(); conn.setDoOutput(true); InputStream inputStream = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8"); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } String result = sb.toString(); return result; }
Code Sample 2:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); String year = req.getParameter("year").toString(); String round = req.getParameter("round").toString(); resp.getWriter().println("<html><body>"); resp.getWriter().println("Searching for : " + year + ", " + round + "<br/>"); StringBuffer sb = new StringBuffer("http://www.dfb.de/bliga/bundes/archiv/"); sb.append(year).append("/xml/blm_e_").append(round).append("_").append(year.substring(2, 4)).append(".xml"); resp.getWriter().println(sb.toString() + "<br/><br/>"); try { URL url = new URL(sb.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer xml = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { xml.append(line); } Document document = DocumentHelper.parseText(xml.toString()); List termine = document.selectNodes("//ergx/termin"); int index = 1; for (Object termin : termine) { Element terminNode = (Element) termin; resp.getWriter().println("Termin " + index + " : " + terminNode.element("datum").getText() + "<br/>"); resp.getWriter().println("Heim:" + terminNode.element("teama").getText() + "<br/>"); resp.getWriter().println("Gast:" + terminNode.element("teamb").getText() + "<br/>"); resp.getWriter().println("Ergebnis:" + terminNode.element("punkte_a").getText() + ":" + terminNode.element("punkte_b").getText() + "<br/>"); resp.getWriter().println("<br/>"); index++; } resp.getWriter().println(); resp.getWriter().println("</body></html>"); reader.close(); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } catch (DocumentException ex) { throw new RuntimeException(ex); } }
|
00
|
Code Sample 1:
private void dumpFile(File repository, File copy) { try { if (copy.exists() && !copy.delete()) { throw new RuntimeException("can't delete copy: " + copy); } printFile("Real Archive File", repository); new ZipArchive(repository.getPath()); IOUtils.copyFiles(repository, copy); printFile("Copy Archive File", copy); new ZipArchive(copy.getPath()); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
protected void initializeFromURL(URL url, AVList params) throws IOException { URLConnection connection = url.openConnection(); String message = this.validateURLConnection(connection, SHAPE_CONTENT_TYPES); if (message != null) { throw new IOException(message); } this.shpChannel = Channels.newChannel(WWIO.getBufferedInputStream(connection.getInputStream())); URLConnection shxConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), INDEX_FILE_SUFFIX)); if (shxConnection != null) { message = this.validateURLConnection(shxConnection, INDEX_CONTENT_TYPES); if (message != null) Logging.logger().warning(message); else { InputStream shxStream = this.getURLStream(shxConnection); if (shxStream != null) this.shxChannel = Channels.newChannel(WWIO.getBufferedInputStream(shxStream)); } } URLConnection prjConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), PROJECTION_FILE_SUFFIX)); if (prjConnection != null) { message = this.validateURLConnection(prjConnection, PROJECTION_CONTENT_TYPES); if (message != null) Logging.logger().warning(message); else { InputStream prjStream = this.getURLStream(prjConnection); if (prjStream != null) this.prjChannel = Channels.newChannel(WWIO.getBufferedInputStream(prjStream)); } } this.setValue(AVKey.DISPLAY_NAME, url.toString()); this.initialize(params); URL dbfURL = WWIO.makeURL(WWIO.replaceSuffix(url.toString(), ATTRIBUTE_FILE_SUFFIX)); if (dbfURL != null) { try { this.attributeFile = new DBaseFile(dbfURL); } catch (Exception e) { } } }
|
00
|
Code Sample 1:
@Before public void setUp() throws Exception { configureSslSocketConnector(); SecurityHandler securityHandler = createBasicAuthenticationSecurityHandler(); HandlerList handlerList = new HandlerList(); handlerList.addHandler(securityHandler); handlerList.addHandler(new AbstractHandler() { @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } }); server.addHandler(handlerList); server.start(); }
Code Sample 2:
public static String md5(String plainText) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } ret = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ret; }
|
00
|
Code Sample 1:
private static String hash(String string) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (Exception e) { return null; } try { md.update(string.getBytes("UTF-8")); } catch (Exception e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public void readData(RowSetInternal caller) throws SQLException { Connection con = null; try { CachedRowSet crs = (CachedRowSet) caller; if (crs.getPageSize() == 0 && crs.size() > 0) { crs.close(); } writerCalls = 0; userCon = false; con = this.connect(caller); if (con == null || crs.getCommand() == null) throw new SQLException(resBundle.handleGetObject("crsreader.connecterr").toString()); try { con.setTransactionIsolation(crs.getTransactionIsolation()); } catch (Exception ex) { ; } PreparedStatement pstmt = con.prepareStatement(crs.getCommand()); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } if (crs.getCommand().toLowerCase().indexOf("select") != -1) { ResultSet rs = pstmt.executeQuery(); if (crs.getPageSize() == 0) { crs.populate(rs); } else { pstmt = con.prepareStatement(crs.getCommand(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } rs = pstmt.executeQuery(); crs.populate(rs, startPosition); } rs.close(); } else { pstmt.executeUpdate(); } pstmt.close(); try { con.commit(); } catch (SQLException ex) { ; } if (getCloseConnection() == true) con.close(); } catch (SQLException ex) { throw ex; } finally { try { if (con != null && getCloseConnection() == true) { try { if (!con.getAutoCommit()) { con.rollback(); } } catch (Exception dummy) { } con.close(); con = null; } } catch (SQLException e) { } } }
|
00
|
Code Sample 1:
public static final void sequence(int[] list, int above) { int temp, max, min; boolean tag = true; for (int i = list.length - 1; i >= 0; i--) { for (int j = 0; j < i; j++) { if (above < 0) { if (list[j] < list[j + 1]) { temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; tag = true; } } else { if (list[j] > list[j + 1]) { temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; tag = true; } } } if (tag == false) break; } }
Code Sample 2:
private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); }
|
11
|
Code Sample 1:
public static String crypt(String senha) { String md5 = null; MessageDigest md; try { md = MessageDigest.getInstance(CRYPT_ALGORITHM); md.update(senha.getBytes()); Hex hex = new Hex(); md5 = new String(hex.encode(md.digest())); } catch (NoSuchAlgorithmException e) { logger.error(ResourceUtil.getLOGMessage("_nls.mensagem.geral.log.crypt.no.such.algorithm", CRYPT_ALGORITHM)); } return md5; }
Code Sample 2:
public void run() { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); ChannelMap cm = new ChannelMap(); for (int i = 0; i < picm.NumberOfChannels(); i++) { cm.Add(picm.GetName(i)); } String[] folder = picm.GetFolderList(); for (int i = 0; i < folder.length; i++) { cm.AddFolder(folder[i]); } sink.Request(cm, picm.GetRequestStart(), picm.GetRequestDuration(), picm.GetRequestReference()); cm = sink.Fetch(timeout); if (cm.GetIfFetchTimedOut()) { System.err.println("Signature Data Fetch Timed Out!"); picm.Clear(); } else { md.reset(); folder = cm.GetFolderList(); for (int i = 0; i < folder.length; i++) picm.AddFolder(folder[i]); int sigIdx = -1; for (int i = 0; i < cm.NumberOfChannels(); i++) { String chan = cm.GetName(i); if (chan.endsWith("/_signature")) { sigIdx = i; continue; } int idx = picm.GetIndex(chan); if (idx == -1) idx = picm.Add(chan); picm.PutTimeRef(cm, i); picm.PutDataRef(idx, cm, i); md.update(cm.GetData(i)); md.update((new Double(cm.GetTimeStart(i))).toString().getBytes()); } if (cm.NumberOfChannels() > 0) { byte[] amd = md.digest(signature.getBytes()); if (sigIdx >= 0) { if (MessageDigest.isEqual(amd, cm.GetDataAsByteArray(sigIdx)[0])) { System.err.println(pluginName + ": signature matched for: " + cm.GetName(0)); } else { System.err.println(pluginName + ": failed signature test, sending null response"); picm.Clear(); } } else { System.err.println(pluginName + ": _signature attached for: " + cm.GetName(0)); int idx = picm.Add("_signature"); picm.PutTime(0., 0.); picm.PutDataAsByteArray(idx, amd); } } } plugin.Flush(picm); } catch (Exception e) { e.printStackTrace(); } if (threadStack.size() < 4) threadStack.push(this); else sink.CloseRBNBConnection(); }
|
00
|
Code Sample 1:
public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { } } } return url; }
Code Sample 2:
public static String genetateSHA256(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] passWd = md.digest(); String hex = toHex(passWd); return hex; }
|
00
|
Code Sample 1:
protected BufferedImage handleFirenzeException() { if (params.uri.indexOf("bncf.firenze.sbn.it") != -1) try { params.uri = params.uri.replace("http://opac.bncf.firenze.sbn.it/mdigit/jsp/mdigit.jsp?idr", "http://teca.bncf.firenze.sbn.it/TecaViewer/index.jsp?RisIdr"); URLConnection connection = new URL(params.uri).openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String url = null; params.uri = "addPage('http://opac.bncf.firenze.sbn.it/php/xlimage/XLImageRV.php"; while ((url = reader.readLine()) != null) { int index = url.indexOf(params.uri); if (index != -1) { url = url.substring(url.indexOf("'") + 1, url.lastIndexOf("'")); break; } } connection = new URL(url).openConnection(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); params.uri = "<input type=\"image\" border=\"0\" name=\"tpos\" width=\""; while ((url = reader.readLine()) != null) { int index = url.indexOf(params.uri); if (index != -1) { url = url.substring(url.indexOf(" src=\"") + 6, url.lastIndexOf("\" alt=\"")).replace("&z=2", "&z=32").replace("&z=4", "&z=64").replace("&z=8", "&z=128"); break; } } if (url != null) { connection = new URL(url).openConnection(); return processNewUri(connection); } } catch (Exception e) { } return null; }
Code Sample 2:
public static Model downloadModel(String url) { Model model = ModelFactory.createDefaultModel(); try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestProperty("Accept", "application/rdf+xml, */*;q=.1"); httpConnection.setRequestProperty("Accept-Language", "en"); } InputStream in = connection.getInputStream(); model.read(in, url); in.close(); return model; } catch (MalformedURLException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } catch (IOException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public boolean isServerAlive(String pStrURL) { boolean isAlive; long t1 = System.currentTimeMillis(); try { URL url = new URL(pStrURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { logger.fine(inputLine); } logger.info("** Connection successful.. **"); in.close(); isAlive = true; } catch (Exception e) { logger.info("** Connection failed.. **"); e.printStackTrace(); isAlive = false; } long t2 = System.currentTimeMillis(); logger.info("Time taken to check connection: " + (t2 - t1) + " ms."); return isAlive; }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
|
00
|
Code Sample 1:
private void DrawModel(Graphics offg, int obj_num, boolean object, float h, float s, int vt_num, int fc_num) { int px[] = new int[3]; int py[] = new int[3]; int count = 0; int tmp[] = new int[fc_num]; double tmp_depth[] = new double[fc_num]; rotate(vt_num); offg.setColor(Color.black); for (int i = 0; i < fc_num; i++) { double a1 = fc[i].vt1.x - fc[i].vt0.x; double a2 = fc[i].vt1.y - fc[i].vt0.y; double a3 = fc[i].vt1.z - fc[i].vt0.z; double b1 = fc[i].vt2.x - fc[i].vt1.x; double b2 = fc[i].vt2.y - fc[i].vt1.y; double b3 = fc[i].vt2.z - fc[i].vt1.z; fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; fc[i].nz = a1 * b2 - a2 * b1; if (fc[i].nz < 0) { fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; tmp[count] = i; tmp_depth[count] = fc[i].getDepth(); count++; } } int lim = count - 1; do { int m = 0; for (int n = 0; n <= lim - 1; n++) { if (tmp_depth[n] < tmp_depth[n + 1]) { double t = tmp_depth[n]; tmp_depth[n] = tmp_depth[n + 1]; tmp_depth[n + 1] = t; int ti = tmp[n]; tmp[n] = tmp[n + 1]; tmp[n + 1] = ti; m = n; } } lim = m; } while (lim != 0); for (int m = 0; m < count; m++) { int i = tmp[m]; double l = Math.sqrt(fc[i].nx * fc[i].nx + fc[i].ny * fc[i].ny + fc[i].nz * fc[i].nz); test(offg, i, l, h, s); px[0] = (int) (fc[i].vt0.x * m_Scale + centerp.x); py[0] = (int) (-fc[i].vt0.y * m_Scale + centerp.y); px[1] = (int) (fc[i].vt1.x * m_Scale + centerp.x); py[1] = (int) (-fc[i].vt1.y * m_Scale + centerp.y); px[2] = (int) (fc[i].vt2.x * m_Scale + centerp.x); py[2] = (int) (-fc[i].vt2.y * m_Scale + centerp.y); offg.fillPolygon(px, py, 3); } if (labelFlag && object) { offg.setFont(Fonts.FONT_REAL); offg.drawString(d_con.getPointerData().getRealObjName(obj_num), (int) ((fc[0].vt0.x + 10) * m_Scale + centerp.x), (int) (-(fc[0].vt0.y + 10) * m_Scale + centerp.y)); } }
Code Sample 2:
public static void main(String args[]) { if (args.length < 1) { printUsage(); } URL url; BufferedReader in = null; try { url = new URL(args[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if (responseCode == 200) { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } else { System.out.println("Response code " + responseCode + " means there was an error reading url " + args[0]); } } catch (IOException e) { System.err.println("IOException attempting to read url " + args[0]); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception ignore) { } } } }
|
00
|
Code Sample 1:
private void onCheckConnection() { BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { public void run() { String baseUrl; if (_rdoSRTM3FtpUrl.getSelection()) { } else { baseUrl = _txtSRTM3HttpUrl.getText().trim(); try { final URL url = new URL(baseUrl); final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.connect(); final int response = urlConn.getResponseCode(); final String responseMessage = urlConn.getResponseMessage(); final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage }); MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message); } catch (final IOException e) { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl)); e.printStackTrace(); } } } }); }
Code Sample 2:
public void deletePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
11
|
Code Sample 1:
public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } }
Code Sample 2:
private void preprocessImages(GeoImage[] detailedImages) throws IOException { for (int i = 0; i < detailedImages.length; i++) { BufferedImage img = loadImage(detailedImages[i].getPath()); detailedImages[i].setLatDim(img.getHeight()); detailedImages[i].setLonDim(img.getWidth()); freeImage(img); String fileName = detailedImages[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("filename " + tmp); File worldFile = new File(tmp); if (!worldFile.exists()) { System.out.println("Rez: Could not find file: " + tmp); debug("Rez: Could not find directory: " + tmp); throw new IOException("File not Found"); } BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLonSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLonExtent(detailedImages[i].getLonSpacing() * ((double) detailedImages[i].getLonDim() - 1d)); System.out.println("setLonExtent " + detailedImages[i].getLonExtent()); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLatSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLatExtent(detailedImages[i].getLatSpacing() * ((double) detailedImages[i].getLatDim() - 1d)); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); detailedImages[i].setPath(tmp); DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } else { System.out.println("Rez: ERROR: World file for image is null"); } } }
|
11
|
Code Sample 1:
public static String translate(String s, String type) { try { String result = null; URL url = new URL("http://www.excite.co.jp/world/english/"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("before=" + URLEncoder.encode(s, "SJIS") + "&wb_lp="); out.print(type); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "SJIS")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("name=\"after\""); if (textPos >= 0) { int ltrPos = inputLine.indexOf(">", textPos + 11); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 1); if (closePos >= 0) { result = inputLine.substring(ltrPos + 1, closePos); break; } else { result = inputLine.substring(ltrPos + 1); break; } } } } in.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
public String sendRequest(java.lang.String servletName, java.lang.String request) { String reqxml = ""; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = ""; myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); String req1xml = request; java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println("#########***********$$$$$$$$##########" + req1xml); dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8"); retdoc = (new org.jdom.input.SAXBuilder()).build(br); } catch (java.net.ConnectException conexp) { javax.swing.JOptionPane.showMessageDialog(null, newgen.presentation.NewGenMain.getAppletInstance().getMyResource().getString("ConnectExceptionMessage"), "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE); } catch (Exception exp) { exp.printStackTrace(System.out); TroubleShootConnectivity troubleShoot = new TroubleShootConnectivity(); } System.out.println(reqxml); return (new org.jdom.output.XMLOutputter()).outputString(retdoc); }
|
11
|
Code Sample 1:
public void processSaveHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_HOLDING " + "SET " + " full_name_HOLDING=?, " + " NAME_HOLDING=? " + "WHERE ID_HOLDING = ? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); RsetTools.setLong(ps, num++, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); processInsertRelatedCompany(dbDyn, holdingBean, authSession); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
00
|
Code Sample 1:
public static Vector getMetaKeywordsFromURL(String p_url) throws Exception { URL x_url = new URL(p_url); URLConnection x_conn = x_url.openConnection(); InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream()); BufferedReader x_reader = new BufferedReader(x_is_reader); String x_line = null; String x_lc_line = null; int x_body = -1; String x_keyword_list = null; int x_keywords = -1; String[] x_meta_keywords = null; while ((x_line = x_reader.readLine()) != null) { x_lc_line = x_line.toLowerCase(); x_keywords = x_lc_line.indexOf("<meta name=\"keywords\" content=\""); if (x_keywords != -1) { x_keywords = "<meta name=\"keywords\" content=\"".length(); x_keyword_list = x_line.substring(x_keywords, x_line.indexOf("\">", x_keywords)); x_keyword_list = x_keyword_list.replace(',', ' '); x_meta_keywords = Parser.extractWordsFromSpacedList(x_keyword_list); } x_body = x_lc_line.indexOf("<body"); if (x_body != -1) break; } Vector x_vector = new Vector(x_meta_keywords.length); for (int i = 0; i < x_meta_keywords.length; i++) x_vector.add(x_meta_keywords[i]); return x_vector; }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private void readParameterTable() { if (this.parameters != null) return; parameters = new GribPDSParameter[NPARAMETERS]; int center; int subcenter; int number; try { BufferedReader br; if (filename != null && filename.length() > 0) { GribPDSParamTable tab = (GribPDSParamTable) fileTabMap.get(filename); if (tab != null) { this.parameters = tab.parameters; return; } } if (url != null) { InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); } else { br = new BufferedReader(new FileReader("tables\\" + filename)); } String line = br.readLine(); String[] tableDefArr = SmartStringArray.split(":", line); center = Integer.parseInt(tableDefArr[1].trim()); subcenter = Integer.parseInt(tableDefArr[2].trim()); number = Integer.parseInt(tableDefArr[3].trim()); while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() == 0 || line.startsWith("//")) continue; GribPDSParameter parameter = new GribPDSParameter(); tableDefArr = SmartStringArray.split(":", line); parameter.number = Integer.parseInt(tableDefArr[0].trim()); parameter.name = tableDefArr[1].trim(); if (tableDefArr[2].indexOf('[') == -1) { parameter.description = parameter.unit = tableDefArr[2].trim(); } else { String[] arr2 = SmartStringArray.split("[", tableDefArr[2]); parameter.description = arr2[0].trim(); parameter.unit = arr2[1].substring(0, arr2[1].lastIndexOf(']')).trim(); } if (!this.setParameter(parameter)) { System.err.println("Warning, bad parameter ignored (" + filename + "): " + parameter.toString()); } } if (filename != null && filename.length() > 0) { GribPDSParamTable loadedTable = new GribPDSParamTable(filename, center, subcenter, number, this.parameters); fileTabMap.put(filename, loadedTable); } } catch (IOException ioError) { System.err.println("An error occurred in GribPDSParamTable while " + "trying to open the parameter table " + filename + " : " + ioError); } }
Code Sample 2:
public JythonWrapperAction(AActionBO.ActionDTO dto, URL url) throws IOException { super(dto); InputStream in = url.openStream(); InputStreamReader rin = new InputStreamReader(in); BufferedReader reader = new BufferedReader(rin); StringBuffer s = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { s.append(str); s.append("\n"); } in.close(); script = s.toString(); }
|
00
|
Code Sample 1:
public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) { final byte[] resourceBytes = readResource(owningClass, resourceName); final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes); final File destinationFile = new File(destinationDir, resourceName); final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(destinationFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } }
Code Sample 2:
public java.io.Serializable getContent() throws org.osid.repository.RepositoryException { logger.logMethod(); if (!this.cached) { logger.logTrace("not cached.. getting content"); Object object = this.asset.getContent(); if (object instanceof String) { String s = (String) object; if (s.startsWith("http://")) { try { java.net.URL url = new java.net.URL(s); java.io.InputStream is = url.openStream(); java.io.File file = getCacheFile(); java.io.FileOutputStream fos = new java.io.FileOutputStream(file); int len; byte[] b = new byte[10240]; this.length = 0; while ((len = is.read(b)) >= 0) { fos.write(b, 0, len); this.length += len; } fos.close(); is.close(); java.net.URLConnection urlc = new java.net.URL(s).openConnection(); this.lastModified = urlc.getLastModified(); this.mimeType = urlc.getContentType(); } catch (java.io.IOException ie) { logger.logError("error writing file", ie); } } } this.cached = true; } else { logger.logTrace("cached.."); } try { return (new SerializableInputStream(new java.io.FileInputStream(getCacheFile()))); } catch (java.io.IOException ie) { logger.logError("cannot get content", ie); throw new org.osid.repository.RepositoryException(org.osid.repository.RepositoryException.OPERATION_FAILED); } }
|
00
|
Code Sample 1:
protected static String fileName2md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes("iso-8859-1")); byte[] byteHash = md.digest(); md.reset(); StringBuffer resultString = new StringBuffer(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int i = 0; i < ex.getStackTrace().length; i++) Logger.error(" " + ex.getStackTrace()[i].toString()); ex.printStackTrace(); } return String.valueOf(Math.random() * Long.MAX_VALUE); }
Code Sample 2:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
|
00
|
Code Sample 1:
protected InputStream getInputStream(URL url) { InputStream is = null; if (url != null) { try { is = url.openStream(); } catch (Exception ex) { } } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (is == null) { try { is = classLoader.getResourceAsStream("osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("/osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("META-INF/osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("/META-INF/osworkflow.xml"); } catch (Exception e) { } } return is; }
Code Sample 2:
public MemoryBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
|
11
|
Code Sample 1:
public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { LOG.debug("[sgkim] copy - start"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in = null; OutputStream out = null; try { LOG.debug("[sgkim] srcFS: " + srcFS + ", src: " + src); in = srcFS.open(src); LOG.debug("[sgkim] dstFS: " + dstFS + ", dst: " + dst); out = dstFS.create(dst, overwrite); LOG.debug("[sgkim] copyBytes - start"); IOUtils.copyBytes(in, out, conf, true); LOG.debug("[sgkim] copyBytes - end"); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } LOG.debug("[sgkim] copy - end"); if (deleteSource) { return srcFS.delete(src, true); } else { return true; } }
Code Sample 2:
public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
|
00
|
Code Sample 1:
public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); }
Code Sample 2:
public static boolean downloadFile(String url, String destination) { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; try { java.net.URL fileurl; try { fileurl = new java.net.URL(url); } catch (MalformedURLException e) { return false; } bi = new BufferedInputStream(fileurl.openStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int readedbyte; while ((readedbyte = bi.read()) != -1) { bo.write(readedbyte); } bo.flush(); } catch (IOException ex) { return false; } finally { try { bi.close(); bo.close(); } catch (Exception ex) { } } return true; }
|
00
|
Code Sample 1:
public void issue(String licenseId, Map answers, String lang) throws IOException { String issueUrl = this.rest_root + "/license/" + licenseId + "/issue"; String answer_doc = "<answers>\n<license-" + licenseId + ">"; Iterator keys = answers.keySet().iterator(); try { String current = (String) keys.next(); while (true) { answer_doc += "<" + current + ">" + (String) answers.get(current) + "</" + current + ">\n"; current = (String) keys.next(); } } catch (NoSuchElementException e) { } answer_doc += "</license-" + licenseId + ">\n</answers>\n"; String post_data; try { post_data = URLEncoder.encode("answers", "UTF-8") + "=" + URLEncoder.encode(answer_doc, "UTF-8"); } catch (UnsupportedEncodingException e) { return; } URL post_url; try { post_url = new URL(issueUrl); } catch (MalformedURLException e) { return; } URLConnection conn = post_url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(post_data); wr.flush(); try { this.license_doc = this.parser.build(conn.getInputStream()); } catch (JDOMException e) { System.out.print("Danger Will Robinson, Danger!"); } return; }
Code Sample 2:
public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
|
11
|
Code Sample 1:
public static void copyFile(String fromFile, String toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) { try { FileChannel in = new FileInputStream(source).getChannel(); if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); FileChannel out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } }
|
00
|
Code Sample 1:
public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } }
Code Sample 2:
public String output(final ComponentParameter compParameter) { InputStream inputStream; try { final URL url = new URL("http://xml.weather.yahoo.com/forecastrss?p=" + getPagelet().getOptionProperty("_weather_code") + "&u=c"); inputStream = url.openStream(); } catch (final IOException e) { return e.getMessage(); } final StringBuilder sb = new StringBuilder(); new AbstractXmlDocument(inputStream) { @Override protected void init() throws Exception { final Element root = getRoot(); final Namespace ns = root.getNamespaceForPrefix("yweather"); final Element channel = root.element("channel"); final String link = channel.elementText("link"); final Element item = channel.element("item"); Element ele = item.element(QName.get("condition", ns)); if (ele == null) { sb.append("ERROR"); return; } final String imgPath = getPagelet().getColumnBean().getPortalBean().getCssResourceHomePath(compParameter) + "/images/yahoo/"; String text, image; Date date = new SimpleDateFormat(YahooWeatherUtils.RFC822_MASKS[1], Locale.US).parse(ele.attributeValue("date")); final int temp = Integer.parseInt(ele.attributeValue("temp")); int code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append("<div style=\"line-height: normal;\"><a target=\"_blank\" href=\"").append(link).append("\"><img src=\""); sb.append(image).append("\" /></a>"); sb.append(YahooWeatherUtils.formatHour(date)).append(" - "); sb.append(text).append(" - ").append(temp).append("℃").append("<br>"); final Iterator<?> it = item.elementIterator(QName.get("forecast", ns)); while (it.hasNext()) { ele = (Element) it.next(); date = new SimpleDateFormat("dd MMM yyyy", Locale.US).parse(ele.attributeValue("date")); final int low = Integer.parseInt(ele.attributeValue("low")); final int high = Integer.parseInt(ele.attributeValue("high")); code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append(YahooWeatherUtils.formatWeek(date)).append(" ( "); sb.append(text).append(". "); sb.append(low).append("℃~").append(high).append("℃"); sb.append(" )<br>"); } sb.append("</div>"); } }; return sb.toString(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.